blob: 8c46a7e4038c58569e85c4ec0adef3a636fca708 [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"
Elliott Hughes54e7df12011-09-16 11:47:04 -070026#include "monitor.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070027#include "oat_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070028#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080029#include "object_utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070030#include "runtime.h"
Ian Rogers466bb252011-10-14 03:29:56 -070031#include "runtime_support.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070032#include "ScopedLocalRef.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070033#include "space.h"
Brian Carlstrom40381fb2011-10-19 14:13:40 -070034#include "stack_indirect_reference_table.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070035#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070036#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070037#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070038#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070039
40namespace art {
41
Elliott Hughes4a2b4172011-09-20 17:08:25 -070042namespace {
43
Elliott Hughes362f9bc2011-10-17 18:56:41 -070044void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070045void ThrowNoClassDefFoundError(const char* fmt, ...) {
46 va_list args;
47 va_start(args, fmt);
48 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
49 va_end(args);
50}
51
Elliott Hughes362f9bc2011-10-17 18:56:41 -070052void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughese555dc02011-09-25 10:46:35 -070053void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070054 va_list args;
55 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070056 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070057 va_end(args);
58}
59
Elliott Hughes362f9bc2011-10-17 18:56:41 -070060void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070061void ThrowLinkageError(const char* fmt, ...) {
62 va_list args;
63 va_start(args, fmt);
64 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
65 va_end(args);
66}
67
Ian Rogers9f1ab122011-12-12 08:52:43 -080068void ThrowNoSuchMethodError(bool is_direct, Class* c, const StringPiece& name,
69 const StringPiece& signature) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080070 ClassHelper kh(c);
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070071 std::ostringstream msg;
Ian Rogers9f1ab122011-12-12 08:52:43 -080072 msg << "no " << (is_direct ? "direct" : "virtual") << " method " << name << "." << signature
73 << " in class " << kh.GetDescriptor() << " or its superclasses";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080074 std::string location(kh.GetLocation());
75 if (!location.empty()) {
76 msg << " (defined in " << location << ")";
Elliott Hughescc5f9a92011-09-28 19:17:29 -070077 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070078 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070079}
80
Ian Rogersb067ac22011-12-13 18:05:09 -080081void ThrowNoSuchFieldError(const StringPiece& scope, Class* c, const StringPiece& type,
Ian Rogers9f1ab122011-12-12 08:52:43 -080082 const StringPiece& name) {
83 ClassHelper kh(c);
84 std::ostringstream msg;
Ian Rogersb067ac22011-12-13 18:05:09 -080085 msg << "no " << scope << "field " << name << " of type " << type
Ian Rogers9f1ab122011-12-12 08:52:43 -080086 << " in class " << kh.GetDescriptor() << " or its superclasses";
87 std::string location(kh.GetLocation());
88 if (!location.empty()) {
89 msg << " (defined in " << location << ")";
90 }
91 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchFieldError;", msg.str().c_str());
92}
93
Ian Rogerscab01012012-01-10 17:35:46 -080094void ThrowNullPointerException(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
95void ThrowNullPointerException(const char* fmt, ...) {
96 va_list args;
97 va_start(args, fmt);
98 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NullPointerException;", fmt, args);
99 va_end(args);
100}
101
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700102void ThrowEarlierClassFailure(Class* c) {
103 /*
104 * The class failed to initialize on a previous attempt, so we want to throw
105 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
106 * failed in verification, in which case v2 5.4.1 says we need to re-throw
107 * the previous error.
108 */
109 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
110
111 if (c->GetVerifyErrorClass() != NULL) {
112 // TODO: change the verifier to store an _instance_, with a useful detail message?
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800113 ClassHelper ve_ch(c->GetVerifyErrorClass());
114 std::string error_descriptor(ve_ch.GetDescriptor());
115 Thread::Current()->ThrowNewException(error_descriptor.c_str(), PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700116 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800117 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700118 }
119}
120
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700121void WrapExceptionInInitializer() {
122 JNIEnv* env = Thread::Current()->GetJniEnv();
123
124 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
125 CHECK(cause.get() != NULL);
126
127 env->ExceptionClear();
128
129 // TODO: add java.lang.Error to JniConstants?
130 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
131 CHECK(error_class.get() != NULL);
132 if (env->IsInstanceOf(cause.get(), error_class.get())) {
133 // We only wrap non-Error exceptions; an Error can just be used as-is.
134 env->Throw(cause.get());
135 return;
136 }
137
138 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
139 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
140 CHECK(eiie_class.get() != NULL);
141
142 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
143 CHECK(mid != NULL);
144
145 ScopedLocalRef<jthrowable> eiie(env,
146 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
147 env->Throw(eiie.get());
148}
149
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800150static size_t Hash(const char* s) {
151 // This is the java.lang.String hashcode for convenience, not interoperability.
152 size_t hash = 0;
153 for (; *s != '\0'; ++s) {
154 hash = hash * 31 + *s;
155 }
156 return hash;
157}
158
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700159} // namespace
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700160
Elliott Hughes418d20f2011-09-22 14:00:39 -0700161const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700162 "Ljava/lang/Class;",
163 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700164 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700165 "[Ljava/lang/Object;",
166 "Ljava/lang/String;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700167 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700168 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700169 "Ljava/lang/reflect/Field;",
170 "Ljava/lang/reflect/Method;",
Ian Rogers466bb252011-10-14 03:29:56 -0700171 "Ljava/lang/reflect/Proxy;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700172 "Ljava/lang/ClassLoader;",
173 "Ldalvik/system/BaseDexClassLoader;",
174 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700175 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700176 "Z",
177 "B",
178 "C",
179 "D",
180 "F",
181 "I",
182 "J",
183 "S",
184 "V",
185 "[Z",
186 "[B",
187 "[C",
188 "[D",
189 "[F",
190 "[I",
191 "[J",
192 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700193 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700194};
195
Elliott Hughes5f791332011-09-15 17:45:30 -0700196class ObjectLock {
197 public:
198 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
199 CHECK(object != NULL);
200 obj_->MonitorEnter(self_);
201 }
202
203 ~ObjectLock() {
204 obj_->MonitorExit(self_);
205 }
206
207 void Wait() {
208 return Monitor::Wait(self_, obj_, 0, 0, false);
209 }
210
211 void Notify() {
212 obj_->Notify();
213 }
214
215 void NotifyAll() {
216 obj_->NotifyAll();
217 }
218
219 private:
220 Thread* self_;
221 Object* obj_;
222 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
223};
224
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800225ClassLinker* ClassLinker::Create(const std::string& boot_class_path, InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700226 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800227 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700228 class_linker->Init(boot_class_path);
229 return class_linker.release();
230}
231
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800232ClassLinker* ClassLinker::Create(InternTable* intern_table) {
233 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700234 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700235 return class_linker.release();
236}
237
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800238ClassLinker::ClassLinker(InternTable* intern_table)
239 : dex_lock_("ClassLinker dex lock"),
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700240 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700241 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700242 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700243 init_done_(false),
244 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700245 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700246}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700247
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700248void CreateClassPath(const std::string& class_path,
249 std::vector<const DexFile*>& class_path_vector) {
250 std::vector<std::string> parsed;
251 Split(class_path, ':', parsed);
252 for (size_t i = 0; i < parsed.size(); ++i) {
253 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700254 if (dex_file == NULL) {
255 LOG(WARNING) << "Failed to open dex file " << parsed[i];
256 } else {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700257 class_path_vector.push_back(dex_file);
258 }
259 }
260}
261
262void ClassLinker::Init(const std::string& boot_class_path) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800263 VLOG(startup) << "ClassLinker::InitFrom entering boot_class_path=" << boot_class_path;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700264
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700265 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700266
Elliott Hughes30646832011-10-13 16:59:46 -0700267 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700268 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
269 CHECK(java_lang_Class.get() != NULL);
270 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700271 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700272 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700273
Elliott Hughes418d20f2011-09-22 14:00:39 -0700274 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700275 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
276 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700277
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700278 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700279 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
280 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700281 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700282 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700283 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700284
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700285 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700286 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
287 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700288
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700289 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700290 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700291
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700292 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700293 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
294 char_array_class->SetComponentType(char_class.get());
295 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700296
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700297 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700298 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
299 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700300 java_lang_String->SetObjectSize(sizeof(String));
301 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400302
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700303 // Create storage for root classes, save away our work so far (requires
304 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700305 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700306 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700307 SetClassRoot(kJavaLangClass, java_lang_Class.get());
308 SetClassRoot(kJavaLangObject, java_lang_Object.get());
309 SetClassRoot(kClassArrayClass, class_array_class.get());
310 SetClassRoot(kObjectArrayClass, object_array_class.get());
311 SetClassRoot(kCharArrayClass, char_array_class.get());
312 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700313
314 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700315 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
316 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
317 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
318 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
319 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
320 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
321 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
322 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700323
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700324 // Create array interface entries to populate once we can load system classes
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700325 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700326
327 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700328 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700329 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700330 IntArray::SetArrayClass(int_array_class.get());
331 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700332
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700333 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700334
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700335 // setup boot_class_path_ and register class_path now that we can
336 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700337 std::vector<const DexFile*> boot_class_path_vector;
338 CreateClassPath(boot_class_path, boot_class_path_vector);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700339 CHECK_NE(0U, boot_class_path_vector.size());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700340 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
341 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700342 CHECK(dex_file != NULL);
343 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700344 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700345
Elliott Hughes80609252011-09-23 17:24:51 -0700346 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700347 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700348 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700349 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700350 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700351 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
352
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700353 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
354 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700355 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700356 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700357 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700358 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700359
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700360 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700361 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700362 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700363 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700364 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700365 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700366
367 // now we can use FindSystemClass
368
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700369 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700370 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700371 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700372
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700373 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700374 java_lang_Object->SetStatus(Class::kStatusNotReady);
375 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700376 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700377 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
378 java_lang_String->SetStatus(Class::kStatusNotReady);
379 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700380 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700381 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
382
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700383 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700384 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
385 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
386
387 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
388 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
389
390 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700391 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700392
393 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
394 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
395
396 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700397 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700398
399 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
400 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
401
402 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
403 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
404
405 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
406 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
407
Elliott Hughes418d20f2011-09-22 14:00:39 -0700408 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700409 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700410
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700411 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700412 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413
414 // Setup the single, global copies of "interfaces" and "iftable"
415 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
416 CHECK(java_lang_Cloneable != NULL);
417 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
418 CHECK(java_io_Serializable != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700419 // We assume that Cloneable/Serializable don't have superinterfaces --
420 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700421 // supers as well.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800422 array_iftable_->Set(0, AllocInterfaceEntry(java_lang_Cloneable));
423 array_iftable_->Set(1, AllocInterfaceEntry(java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700424
Elliott Hughes418d20f2011-09-22 14:00:39 -0700425 // Sanity check Class[] and Object[]'s interfaces
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800426 ClassHelper kh(class_array_class.get(), this);
427 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
428 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
429 kh.ChangeClass(object_array_class.get());
430 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
431 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
Elliott Hughes80609252011-09-23 17:24:51 -0700432 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700433 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700434 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700435 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700436
Elliott Hughes80609252011-09-23 17:24:51 -0700437 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
438 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700439 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700440
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700441 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700442 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700443 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700444
445 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700446 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700447 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700448
Ian Rogers466bb252011-10-14 03:29:56 -0700449 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
450
451 // Create java.lang.reflect.Proxy root
452 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
453 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
454
Brian Carlstrom1f870082011-08-23 16:02:11 -0700455 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700456 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
457 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700458 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700459 java_lang_ref_FinalizerReference->SetAccessFlags(
460 java_lang_ref_FinalizerReference->GetAccessFlags() |
461 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700462 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700463 java_lang_ref_PhantomReference->SetAccessFlags(
464 java_lang_ref_PhantomReference->GetAccessFlags() |
465 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700466 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700467 java_lang_ref_SoftReference->SetAccessFlags(
468 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700469 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700470 java_lang_ref_WeakReference->SetAccessFlags(
471 java_lang_ref_WeakReference->GetAccessFlags() |
472 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700473
Brian Carlstromaded5f72011-10-07 17:15:04 -0700474 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700475 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700476 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700477 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
478
479 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
480 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
481 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
482
483 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
484 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
485 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
486 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
487
488 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700489 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
490 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700491 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700492
Brian Carlstroma663ea52011-08-19 23:33:41 -0700493 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700494
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800495 VLOG(startup) << "ClassLinker::InitFrom exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700496}
497
498void ClassLinker::FinishInit() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800499 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700500
501 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700502 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700503 // as the types of the field can't be resolved prior to the runtime being
504 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700505 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700506 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700507 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
508
Elliott Hughesadb460d2011-10-05 17:02:34 -0700509 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
510
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800511 const DexFile& java_lang_dex = FindDexFile(java_lang_ref_Reference->GetDexCache());
512
Brian Carlstrom16192862011-09-12 17:50:06 -0700513 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800514 FieldHelper fh(pendingNext, this);
515 CHECK_STREQ(fh.GetName(), "pendingNext");
516 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
517 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700518
519 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800520 fh.ChangeField(queue);
521 CHECK_STREQ(fh.GetName(), "queue");
522 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
523 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700524
525 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800526 fh.ChangeField(queueNext);
527 CHECK_STREQ(fh.GetName(), "queueNext");
528 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
529 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700530
531 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800532 fh.ChangeField(referent);
533 CHECK_STREQ(fh.GetName(), "referent");
534 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
535 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700536
537 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800538 fh.ChangeField(zombie);
539 CHECK_STREQ(fh.GetName(), "zombie");
540 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
541 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700542
543 Heap::SetReferenceOffsets(referent->GetOffset(),
544 queue->GetOffset(),
545 queueNext->GetOffset(),
546 pendingNext->GetOffset(),
547 zombie->GetOffset());
548
Brian Carlstroma663ea52011-08-19 23:33:41 -0700549 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700550 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700551 ClassRoot class_root = static_cast<ClassRoot>(i);
552 Class* klass = GetClassRoot(class_root);
553 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700554 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700555 // note SetClassRoot does additional validation.
556 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700557 }
558
Elliott Hughes92f14b22011-10-06 12:29:54 -0700559 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700560
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700561 // disable the slow paths in FindClass and CreatePrimitiveClass now
562 // that Object, Class, and Object[] are setup
563 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700564
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800565 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700566}
567
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700568void ClassLinker::RunRootClinits() {
569 Thread* self = Thread::Current();
570 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
571 Class* c = GetClassRoot(ClassRoot(i));
572 if (!c->IsArrayClass() && !c->IsPrimitive()) {
573 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700574 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700575 }
576 }
577}
578
Brian Carlstromd601af82012-01-06 10:15:19 -0800579bool ClassLinker::GenerateOatFile(const std::string& dex_filename,
580 int oat_fd,
581 const std::string& oat_cache_filename) {
jeffhao262bf462011-10-20 18:36:32 -0700582
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800583 std::string dex2oat_string("/system/bin/dex2oat");
584#ifndef NDEBUG
585 dex2oat_string += 'd';
586#endif
587 const char* dex2oat = dex2oat_string.c_str();
588
589 const char* class_path = Runtime::Current()->GetClassPath().c_str();
590
591 std::string boot_image_option_string("--boot-image=");
592 boot_image_option_string += Heap::GetSpaces()[0]->GetImageFilename();
593 const char* boot_image_option = boot_image_option_string.c_str();
594
595 std::string dex_file_option_string("--dex-file=");
Brian Carlstromd601af82012-01-06 10:15:19 -0800596 dex_file_option_string += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800597 const char* dex_file_option = dex_file_option_string.c_str();
598
Brian Carlstromd601af82012-01-06 10:15:19 -0800599 std::string oat_fd_option_string("--oat-fd=");
Brian Carlstrom866c8622012-01-06 16:35:13 -0800600 StringAppendF(&oat_fd_option_string, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800601 const char* oat_fd_option = oat_fd_option_string.c_str();
602
603 std::string oat_name_option_string("--oat-name=");
604 oat_name_option_string += oat_cache_filename;
605 const char* oat_name_option = oat_name_option_string.c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800606
jeffhao262bf462011-10-20 18:36:32 -0700607 // fork and exec dex2oat
608 pid_t pid = fork();
609 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800610 // no allocation allowed between fork and exec
Ian Rogers725aee52012-01-11 11:56:56 -0800611
612 // change process groups, so we don't get reaped by ProcessManager
613 setpgid(0, 0);
614
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800615 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700616 "--runtime-arg", "-Xms64m",
617 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500618 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800619 "--runtime-arg", class_path,
620 boot_image_option,
621 dex_file_option,
Brian Carlstromd601af82012-01-06 10:15:19 -0800622 oat_fd_option,
623 oat_name_option,
jeffhao262bf462011-10-20 18:36:32 -0700624 NULL);
625
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800626 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
Brian Carlstromd601af82012-01-06 10:15:19 -0800627 return false;
jeffhao262bf462011-10-20 18:36:32 -0700628 } else {
629 // wait for dex2oat to finish
630 int status;
631 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
632 if (got_pid != pid) {
633 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
Brian Carlstromd601af82012-01-06 10:15:19 -0800634 return false;
jeffhao262bf462011-10-20 18:36:32 -0700635 }
636 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800637 LOG(ERROR) << dex2oat << " failed with dex-file=" << dex_filename;
638 return false;
jeffhao262bf462011-10-20 18:36:32 -0700639 }
640 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800641 return true;
jeffhao262bf462011-10-20 18:36:32 -0700642}
643
Brian Carlstrom866c8622012-01-06 16:35:13 -0800644void ClassLinker::RegisterOatFile(const OatFile& oat_file) {
645 MutexLock mu(dex_lock_);
646 RegisterOatFileLocked(oat_file);
647}
648
649void ClassLinker::RegisterOatFileLocked(const OatFile& oat_file) {
650 dex_lock_.AssertHeld();
651 oat_files_.push_back(&oat_file);
652}
653
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700654OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700655 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700656 const Runtime* runtime = Runtime::Current();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800657 VLOG(startup) << "ClassLinker::OpenOat entering";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700658 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800659 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
660 // check the down cast
661 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700662 std::string oat_filename;
663 oat_filename += runtime->GetHostPrefix();
664 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma9f19782011-10-13 00:14:47 -0700665 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBaseAddr());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700666 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700667 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700668 return NULL;
669 }
670 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
671 uint32_t image_oat_checksum = image_header.GetOatChecksum();
672 if (oat_checksum != image_oat_checksum) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800673 LOG(ERROR) << "Failed to match oat file checksum " << std::hex << oat_checksum
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700674 << " to expected oat checksum " << std::hex << oat_checksum
675 << " in image";
676 return NULL;
677 }
Brian Carlstrom866c8622012-01-06 16:35:13 -0800678 RegisterOatFileLocked(*oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800679 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700680 return oat_file;
681}
682
Brian Carlstromae826982011-11-09 01:33:42 -0800683const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
684 for (size_t i = 0; i < oat_files_.size(); i++) {
685 const OatFile* oat_file = oat_files_[i];
686 DCHECK(oat_file != NULL);
Ian Rogers7fe2c692011-12-06 16:35:59 -0800687 if (oat_file->GetOatDexFile(dex_file.GetLocation(), false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800688 return oat_file;
689 }
690 }
691 return NULL;
692}
693
Brian Carlstromd601af82012-01-06 10:15:19 -0800694class LockedFd {
695 public:
696 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
697 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
698 if (fd == -1) {
699 PLOG(ERROR) << "Failed to open file '" << name << "'";
700 return NULL;
701 }
702 fchmod(fd, mode);
703
704 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
705 // try to lock non-blocking so we can log if we need may need to block
706 int result = flock(fd, LOCK_EX | LOCK_NB);
707 if (result == -1) {
708 LOG(WARNING) << "sleeping while locking file " << name;
709 // retry blocking
710 result = flock(fd, LOCK_EX);
711 }
712 if (result == -1) {
713 PLOG(ERROR) << "Failed to lock file '" << name << "'";
714 close(fd);
715 return NULL;
716 }
717 return new LockedFd(fd);
718 }
719
720 int GetFd() const {
721 return fd_;
722 }
723
724 ~LockedFd() {
725 if (fd_ != -1) {
726 int result = flock(fd_, LOCK_UN);
727 if (result == -1) {
728 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
729 }
730 close(fd_);
731 }
732 }
733
734 private:
735 explicit LockedFd(int fd) : fd_(fd) {}
736
737 int fd_;
738};
739
Brian Carlstromae826982011-11-09 01:33:42 -0800740const OatFile* ClassLinker::FindOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700741 MutexLock mu(dex_lock_);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800742 const OatFile* open_oat_file = FindOpenedOatFileForDexFile(dex_file);
743 if (open_oat_file != NULL) {
744 return open_oat_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800745 }
746
Brian Carlstromd601af82012-01-06 10:15:19 -0800747 std::string oat_filename(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
Brian Carlstrom866c8622012-01-06 16:35:13 -0800748 open_oat_file = FindOpenedOatFileFromOatLocation(oat_filename);
749 if (open_oat_file != NULL) {
750 return open_oat_file;
751 }
752
Brian Carlstromd601af82012-01-06 10:15:19 -0800753 while (true) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800754 UniquePtr<const OatFile> oat_file(FindOatFileFromOatLocation(oat_filename));
755 if (oat_file.get() != NULL) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800756 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
757 if (dex_file.GetHeader().checksum_ == oat_dex_file->GetDexFileChecksum()) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800758 RegisterOatFileLocked(*oat_file.get());
759 return oat_file.release();
Brian Carlstromd601af82012-01-06 10:15:19 -0800760 }
761 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
762 << " checksum mismatch with " << dex_file.GetLocation() << " --- regenerating";
763 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
764 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
765 }
766 // Fall through...
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700767 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800768 // Try to generate oat file if it wasn't found or was obsolete.
769 // Note we can be racing with another runtime to do this.
770 std::string oat_cache_filename(GetArtCacheFilenameOrDie(oat_filename));
771 UniquePtr<LockedFd> locked_fd(LockedFd::CreateAndLock(oat_cache_filename, 0644));
772 if (locked_fd.get() == NULL) {
773 LOG(ERROR) << "Failed to create and lock oat file " << oat_cache_filename;
774 return NULL;
Elliott Hughes234da572011-11-03 22:13:06 -0700775 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800776 // Check to see if the fd we opened and locked matches the file in
777 // the filesystem. If they don't, then somebody else unlinked ours
778 // and created a new file, and we need to use that one instead. (If
779 // we caught them between the unlink and the create, we'll get an
780 // ENOENT from the file stat.)
781 struct stat fd_stat;
782 int fd_stat_result = fstat(locked_fd->GetFd(), &fd_stat);
783 if (fd_stat_result != 0) {
784 PLOG(ERROR) << "Failed to fstat file descriptor of oat file " << oat_cache_filename;
785 return NULL;
786 }
787 struct stat file_stat;
788 int file_stat_result = stat(oat_cache_filename.c_str(), &file_stat);
789 if (file_stat_result != 0
790 || fd_stat.st_dev != file_stat.st_dev
791 || fd_stat.st_ino != file_stat.st_ino) {
792 LOG(INFO) << "Opened oat file " << oat_cache_filename << " is stale; sleeping and retrying";
793 usleep(250 * 1000); // if something is hosed, don't peg machine
794 continue;
795 }
796
797 // We have the correct file open and locked. If the file size is
798 // zero, then it was just created by us and we can generate its
799 // contents. If not, someone else created it. Either way, we'll
800 // loop to retry opening the file.
801 if (fd_stat.st_size == 0) {
802 bool success = GenerateOatFile(dex_file.GetLocation(),
803 locked_fd->GetFd(),
804 oat_cache_filename);
805 if (!success) {
806 LOG(ERROR) << "Failed to generate oat file " << oat_cache_filename;
807 return NULL;
808 }
809 }
jeffhao262bf462011-10-20 18:36:32 -0700810 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800811 // Not reached
Brian Carlstromaded5f72011-10-07 17:15:04 -0700812}
813
Brian Carlstromae826982011-11-09 01:33:42 -0800814const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700815 for (size_t i = 0; i < oat_files_.size(); i++) {
816 const OatFile* oat_file = oat_files_[i];
817 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800818 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700819 return oat_file;
820 }
821 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700822 return NULL;
823}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700824
Brian Carlstromae826982011-11-09 01:33:42 -0800825const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800826 const OatFile* oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700827 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800828 if (oat_location.empty() || oat_location[0] != '/') {
829 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700830 return NULL;
831 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700832
Brian Carlstroma9f19782011-10-13 00:14:47 -0700833 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Elliott Hughes95572412011-12-13 18:14:20 -0800834 std::string cache_location(GetArtCacheFilenameOrDie(oat_location));
Brian Carlstromae826982011-11-09 01:33:42 -0800835 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700836 if (oat_file != NULL) {
837 return oat_file;
838 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700839 oat_file = OatFile::Open(cache_location, "", NULL);
840 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800841 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700842 return NULL;
843 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700844 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700845
Brian Carlstromae826982011-11-09 01:33:42 -0800846 CHECK(oat_file != NULL) << oat_location;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700847 return oat_file;
848}
849
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700850void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800851 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700852 CHECK(!init_done_);
853
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700854 const std::vector<Space*>& spaces = Heap::GetSpaces();
855 for (size_t i = 0; i < spaces.size(); i++) {
856 Space* space = spaces[i] ;
857 if (space->IsImageSpace()) {
858 OatFile* oat_file = OpenOat(space);
859 CHECK(oat_file != NULL) << "Failed to open oat file for image";
860 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
861 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
862
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800863 if (i == 0) {
864 // Special case of setting up the String class early so that we can test arbitrary objects
865 // as being Strings or not
866 Class* java_lang_String = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
867 ->AsObjectArray<Class>()->Get(kJavaLangString);
868 String::SetClass(java_lang_String);
869 }
870
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700871 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
872 static_cast<uint32_t>(dex_caches->GetLength()));
873 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700874 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800875 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom89521892011-12-07 22:05:07 -0800876 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
877 const DexFile* dex_file = oat_dex_file->OpenDexFile();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700878 if (dex_file == NULL) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800879 LOG(FATAL) << "Failed to open dex file " << dex_file_location
880 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700881 }
882
Brian Carlstromaded5f72011-10-07 17:15:04 -0700883 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700884
Brian Carlstromdf143242011-10-10 18:05:34 -0700885 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700886 }
887 }
888 }
889
Brian Carlstroma663ea52011-08-19 23:33:41 -0700890 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
891 DCHECK(heap_bitmap != NULL);
892
Brian Carlstroma663ea52011-08-19 23:33:41 -0700893 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700894 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700895
896 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700897 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
898 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700899
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800900 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700901 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
902 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800903 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700904 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700905 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700906 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
907 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
908 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
909 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
910 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
911 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
912 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
913 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700914 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700915 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700916
917 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700918
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800919 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700920}
921
Brian Carlstrom78128a62011-09-15 17:21:19 -0700922void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700923 DCHECK(obj != NULL);
924 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700925 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700926
Elliott Hughesdbb40792011-11-18 17:05:22 -0800927 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700928 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700929 return;
930 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700931 if (obj->IsClass()) {
932 // restore class to ClassLinker::classes_ table
933 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800934 ClassHelper kh(klass, class_linker);
935 bool success = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
Ian Rogers5d76c432011-10-31 21:42:49 -0700936 DCHECK(success);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700937 return;
938 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700939}
940
941// Keep in sync with InitCallback. Anything we visit, we need to
942// reinit references to when reinitializing a ClassLinker from a
943// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700944void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
945 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700946
947 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700948 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700949 }
950
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700951 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700952 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700953 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700954 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700955 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700956 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700957 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700958 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700959
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700960 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700961}
962
Elliott Hughesa2155262011-11-16 16:26:58 -0800963void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
964 MutexLock mu(classes_lock_);
965 typedef Table::const_iterator It; // TODO: C++0x auto
966 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
967 if (!visitor(it->second, arg)) {
968 return;
969 }
970 }
971 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
972 if (!visitor(it->second, arg)) {
973 return;
974 }
975 }
976}
977
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700978ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700979 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700980 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700981 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700982 BooleanArray::ResetArrayClass();
983 ByteArray::ResetArrayClass();
984 CharArray::ResetArrayClass();
985 DoubleArray::ResetArrayClass();
986 FloatArray::ResetArrayClass();
987 IntArray::ResetArrayClass();
988 LongArray::ResetArrayClass();
989 ShortArray::ResetArrayClass();
990 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700991 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700992 STLDeleteElements(&boot_class_path_);
993 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700994}
995
996DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700997 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
998 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700999 return NULL;
1000 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001001 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
1002 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001003 return NULL;
1004 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001005 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
1006 if (strings.get() == NULL) {
1007 return NULL;
1008 }
1009 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
1010 if (types.get() == NULL) {
1011 return NULL;
1012 }
1013 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
1014 if (methods.get() == NULL) {
1015 return NULL;
1016 }
1017 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
1018 if (fields.get() == NULL) {
1019 return NULL;
1020 }
1021 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
1022 if (code_and_direct_methods.get() == NULL) {
1023 return NULL;
1024 }
1025 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
1026 if (initialized_static_storage.get() == NULL) {
1027 return NULL;
1028 }
1029
1030 dex_cache->Init(location.get(),
1031 strings.get(),
1032 types.get(),
1033 methods.get(),
1034 fields.get(),
1035 code_and_direct_methods.get(),
1036 initialized_static_storage.get());
1037 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001038}
1039
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001040CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
1041 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -07001042}
1043
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001044InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
1045 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001046 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
1047 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001048 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001049 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001050}
1051
Brian Carlstrom4873d462011-08-21 15:23:39 -07001052Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
1053 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001054 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001055 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001056 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001057 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001058}
1059
Brian Carlstrom4873d462011-08-21 15:23:39 -07001060Class* ClassLinker::AllocClass(size_t class_size) {
1061 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001062}
1063
Jesse Wilson35baaab2011-08-10 16:18:03 -04001064Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001065 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -07001066}
1067
1068Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001069 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001070}
1071
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001072ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
1073 return ObjectArray<StackTraceElement>::Alloc(
1074 GetClassRoot(kJavaLangStackTraceElementArrayClass),
1075 length);
1076}
1077
Brian Carlstromaded5f72011-10-07 17:15:04 -07001078Class* EnsureResolved(Class* klass) {
1079 DCHECK(klass != NULL);
1080 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -07001081 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001082 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001083 ObjectLock lock(klass);
1084 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001085 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001086 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001087 PrettyDescriptor(klass).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001088 return NULL;
1089 }
1090 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001091 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001092 lock.Wait();
1093 }
1094 }
1095 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001096 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001097 return NULL;
1098 }
1099 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001100 CHECK(klass->IsResolved()) << PrettyClass(klass);
1101 CHECK(!self->IsExceptionPending())
1102 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
1103 return klass;
1104}
1105
Elliott Hughesdb7d5e92011-12-16 18:47:37 -08001106Class* ClassLinker::FindSystemClass(const char* descriptor) {
1107 return FindClass(descriptor, NULL);
1108}
1109
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001110Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
1111 DCHECK(*descriptor != '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001112 Thread* self = Thread::Current();
1113 DCHECK(self != NULL);
1114 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001115 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001116 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1117 // for primitive classes that aren't backed by dex files.
1118 return FindPrimitiveClass(descriptor[0]);
1119 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001120 // Find the class in the loaded classes table.
1121 Class* klass = LookupClass(descriptor, class_loader);
1122 if (klass != NULL) {
1123 return EnsureResolved(klass);
1124 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001125 // Class is not yet loaded.
1126 if (descriptor[0] == '[') {
1127 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001128
Jesse Wilson47daf872011-11-23 11:42:45 -05001129 } else if (class_loader == NULL) {
1130 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1131 if (pair.second != NULL) {
1132 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1133 }
1134
1135 } else if (ClassLoader::UseCompileTimeClassPath()) {
1136 // first try the boot class path
1137 Class* system_class = FindSystemClass(descriptor);
1138 if (system_class != NULL) {
1139 return system_class;
1140 }
1141 CHECK(self->IsExceptionPending());
1142 self->ClearException();
1143
1144 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001145 const std::vector<const DexFile*>& class_path
1146 = ClassLoader::GetCompileTimeClassPath(class_loader);
1147 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001148 if (pair.second != NULL) {
1149 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001150 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001151
1152 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001153 std::string class_name_string(DescriptorToDot(descriptor));
Jesse Wilson47daf872011-11-23 11:42:45 -05001154 ScopedThreadStateChange(self, Thread::kNative);
1155 JNIEnv* env = self->GetJniEnv();
1156 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1157 CHECK(c.get() != NULL);
1158 // TODO: cache method?
1159 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1160 CHECK(mid != NULL);
1161 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1162 if (class_name_object.get() == NULL) {
1163 return NULL;
1164 }
1165 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
Ian Rogers761bfa82012-01-11 10:14:05 -08001166 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid,
1167 class_name_object.get()));
1168 if (env->ExceptionOccurred()) {
1169 env->ExceptionClear(); // Failed to find class fall-through to NCDFE
1170 // TODO: initialize the cause of the NCDFE to this exception
1171 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001172 // broken loader - throw NPE to be compatible with Dalvik
1173 ThrowNullPointerException("ClassLoader.loadClass returned null for %s",
1174 class_name_string.c_str());
1175 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001176 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08001177 // success, return Class*
Ian Rogers6b0870d2011-12-15 19:38:12 -08001178 return Decode<Class*>(env, result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001179 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001180 }
1181
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001182 ThrowNoClassDefFoundError("Class %s not found", PrintableString(StringPiece(descriptor)).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001183 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001184}
1185
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001186Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001187 const ClassLoader* class_loader,
1188 const DexFile& dex_file,
1189 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001190 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001191 // Load the class from the dex file.
1192 if (!init_done_) {
1193 // finish up init of hand crafted class_roots_
1194 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001195 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001196 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001197 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001198 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001199 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001200 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001201 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001202 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001203 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001204 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001205 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001206 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001207 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001208 }
1209 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001210 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001211 }
1212 klass->SetDexCache(FindDexCache(dex_file));
1213 LoadClass(dex_file, dex_class_def, klass, class_loader);
1214 // Check for a pending exception during load
1215 Thread* self = Thread::Current();
1216 if (self->IsExceptionPending()) {
1217 return NULL;
1218 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001219 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001220 klass->SetClinitThreadId(self->GetTid());
1221 // Add the newly loaded class to the loaded classes table.
Ian Rogers5d76c432011-10-31 21:42:49 -07001222 bool success = InsertClass(descriptor, klass.get(), false); // TODO: just return collision
Brian Carlstromaded5f72011-10-07 17:15:04 -07001223 if (!success) {
1224 // We may fail to insert if we raced with another thread.
1225 klass->SetClinitThreadId(0);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001226 klass.reset(LookupClass(descriptor.data(), class_loader));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001227 CHECK(klass.get() != NULL);
1228 return klass.get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001229 }
1230 // Finish loading (if necessary) by finding parents
1231 CHECK(!klass->IsLoaded());
1232 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1233 // Loading failed.
1234 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001235 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001236 lock.NotifyAll();
1237 return NULL;
1238 }
1239 CHECK(klass->IsLoaded());
1240 // Link the class (if necessary)
1241 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001242 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001243 // Linking failed.
1244 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001245 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001246 lock.NotifyAll();
1247 return NULL;
1248 }
1249 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001250
1251 /*
1252 * We send CLASS_PREPARE events to the debugger from here. The
1253 * definition of "preparation" is creating the static fields for a
1254 * class and initializing them to the standard default values, but not
1255 * executing any code (that comes later, during "initialization").
1256 *
1257 * We did the static preparation in LinkClass.
1258 *
1259 * The class has been prepared and resolved but possibly not yet verified
1260 * at this point.
1261 */
1262 Dbg::PostClassPrepare(klass.get());
1263
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001264 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001265}
1266
Brian Carlstrom4873d462011-08-21 15:23:39 -07001267// Precomputes size that will be needed for Class, matching LinkStaticFields
1268size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1269 const DexFile::ClassDef& dex_class_def) {
1270 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001271 size_t num_ref = 0;
1272 size_t num_32 = 0;
1273 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001274 if (class_data != NULL) {
1275 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1276 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001277 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001278 char c = descriptor[0];
1279 if (c == 'L' || c == '[') {
1280 num_ref++;
1281 } else if (c == 'J' || c == 'D') {
1282 num_64++;
1283 } else {
1284 num_32++;
1285 }
1286 }
1287 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001288 // start with generic class data
1289 size_t size = sizeof(Class);
1290 // follow with reference fields which must be contiguous at start
1291 size += (num_ref * sizeof(uint32_t));
1292 // if there are 64-bit fields to add, make sure they are aligned
1293 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1294 if (num_32 != 0) {
1295 // use an available 32-bit field for padding
1296 num_32--;
1297 }
1298 size += sizeof(uint32_t); // either way, we are adding a word
1299 DCHECK_EQ(size, RoundUp(size, 8));
1300 }
1301 // tack on any 64-bit fields now that alignment is assured
1302 size += (num_64 * sizeof(uint64_t));
1303 // tack on any remaining 32-bit fields
1304 size += (num_32 * sizeof(uint32_t));
1305 return size;
1306}
1307
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001308void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001309 // Every kind of method should at least get an invoke stub from the oat_method.
1310 // non-abstract methods also get their code pointers.
1311 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001312 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001313
1314 if (method->IsAbstract()) {
1315 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1316 return;
1317 }
1318 if (method->IsNative()) {
1319 // unregistering restores the dlsym lookup stub
1320 method->UnregisterNative();
1321 return;
1322 }
1323}
1324
Brian Carlstromf615a612011-07-23 12:50:34 -07001325void ClassLinker::LoadClass(const DexFile& dex_file,
1326 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001327 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001328 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001329 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001330 CHECK(klass->GetDexCache() != NULL);
1331 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001332 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001333 CHECK(descriptor != NULL);
1334
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001335 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001336 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001337 // Make sure that none of our runtime-only flags are set.
1338 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001339 klass->SetAccessFlags(access_flags);
1340 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001341 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001342 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001343
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001344 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001345
Ian Rogers0571d352011-11-03 19:51:38 -07001346 // Load fields fields.
1347 const byte* class_data = dex_file.GetClassData(dex_class_def);
1348 if (class_data == NULL) {
1349 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001350 }
Ian Rogers0571d352011-11-03 19:51:38 -07001351 ClassDataItemIterator it(dex_file, class_data);
1352 if (it.NumStaticFields() != 0) {
1353 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1354 }
1355 if (it.NumInstanceFields() != 0) {
1356 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1357 }
1358 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1359 SirtRef<Field> sfield(AllocField());
1360 klass->SetStaticField(i, sfield.get());
1361 LoadField(dex_file, it, klass, sfield);
1362 }
1363 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1364 SirtRef<Field> ifield(AllocField());
1365 klass->SetInstanceField(i, ifield.get());
1366 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001367 }
1368
Brian Carlstromaded5f72011-10-07 17:15:04 -07001369 UniquePtr<const OatFile::OatClass> oat_class;
1370 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001371 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001372 if (oat_file != NULL) {
1373 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1374 if (oat_dex_file != NULL) {
1375 uint32_t class_def_index;
1376 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1377 CHECK(found) << descriptor;
1378 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001379 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001380 }
1381 }
1382 }
Ian Rogers0571d352011-11-03 19:51:38 -07001383 // Load methods.
1384 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001385 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001386 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001387 }
Ian Rogers0571d352011-11-03 19:51:38 -07001388 if (it.NumVirtualMethods() != 0) {
1389 // TODO: append direct methods to class object
1390 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001391 }
Ian Rogers0571d352011-11-03 19:51:38 -07001392 size_t method_index = 0;
1393 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1394 SirtRef<Method> method(AllocMethod());
1395 klass->SetDirectMethod(i, method.get());
1396 LoadMethod(dex_file, it, klass, method);
1397 if (oat_class.get() != NULL) {
1398 LinkCode(method, oat_class.get(), method_index);
1399 }
1400 method_index++;
1401 }
1402 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1403 SirtRef<Method> method(AllocMethod());
1404 klass->SetVirtualMethod(i, method.get());
1405 LoadMethod(dex_file, it, klass, method);
1406 if (oat_class.get() != NULL) {
1407 LinkCode(method, oat_class.get(), method_index);
1408 }
1409 method_index++;
1410 }
1411 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001412}
1413
Ian Rogers0571d352011-11-03 19:51:38 -07001414void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1415 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001416 uint32_t field_idx = it.GetMemberIndex();
1417 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001418 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001419 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001420}
1421
Ian Rogers0571d352011-11-03 19:51:38 -07001422void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1423 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001424 uint32_t method_idx = it.GetMemberIndex();
1425 dst->SetDexMethodIndex(method_idx);
1426 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001427 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001428
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001429
1430 StringPiece method_name(dex_file.GetMethodName(method_id));
1431 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001432 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1433 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001434
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001435 if (method_name == "finalize") {
1436 // Create the prototype for a signature of "()V"
1437 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1438 if (void_string_id != NULL) {
1439 const DexFile::TypeId* void_type_id =
1440 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1441 if (void_type_id != NULL) {
1442 std::vector<uint16_t> no_args;
1443 const DexFile::ProtoId* finalizer_proto =
1444 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1445 if (finalizer_proto != NULL) {
1446 // We have the prototype in the dex file
1447 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1448 klass->SetFinalizable();
1449 } else {
1450 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1451 // The Enum class declares a "final" finalize() method to prevent subclasses from
1452 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1453 // subclasses, so we exclude it here.
1454 // We also want to avoid setting the flag on Object, where we know that finalize() is
1455 // empty.
1456 if (klass_descriptor != "Ljava/lang/Object;" &&
1457 klass_descriptor != "Ljava/lang/Enum;") {
1458 klass->SetFinalizable();
1459 }
1460 }
1461 }
1462 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001463 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001464 }
Ian Rogers0571d352011-11-03 19:51:38 -07001465 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001466 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001467
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001468 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1469 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1470 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1471 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1472 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1473 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001474
Brian Carlstrom934486c2011-07-12 23:42:50 -07001475 // TODO: check for finalize method
Brian Carlstrom934486c2011-07-12 23:42:50 -07001476}
1477
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001478void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001479 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1480 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001481}
1482
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001483void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1484 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001485 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001486 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001487}
1488
Brian Carlstromaded5f72011-10-07 17:15:04 -07001489bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001490 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001491 for (size_t i = 0; i != dex_files_.size(); ++i) {
1492 if (dex_files_[i] == &dex_file) {
1493 return true;
1494 }
1495 }
1496 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001497}
1498
Brian Carlstromaded5f72011-10-07 17:15:04 -07001499bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001500 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001501 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001502}
1503
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001504void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001505 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001506 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001507 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001508 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001509 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001510}
1511
Brian Carlstromaded5f72011-10-07 17:15:04 -07001512void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001513 {
1514 MutexLock mu(dex_lock_);
1515 if (IsDexFileRegisteredLocked(dex_file)) {
1516 return;
1517 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001518 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001519 // Don't alloc while holding the lock, since allocation may need to
1520 // suspend all threads and another thread may need the dex_lock_ to
1521 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001522 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001523 {
1524 MutexLock mu(dex_lock_);
1525 if (IsDexFileRegisteredLocked(dex_file)) {
1526 return;
1527 }
1528 RegisterDexFileLocked(dex_file, dex_cache);
1529 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001530}
1531
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001532void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001533 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001534 RegisterDexFileLocked(dex_file, dex_cache);
1535}
1536
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001537const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001538 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001539 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001540 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1541 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001542 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001543 }
1544 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001545 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001546 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001547}
1548
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001549DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001550 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001551 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001552 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001553 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001554 }
1555 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001556 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001557 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001558}
1559
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001560Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1561 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001562 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001563 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001564 CHECK(primitive_class != NULL);
1565 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001566 primitive_class->SetPrimitiveType(type);
1567 primitive_class->SetStatus(Class::kStatusInitialized);
Ian Rogers5d76c432011-10-31 21:42:49 -07001568 bool success = InsertClass(descriptor, primitive_class, false);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001569 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1570 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001571}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001572
Brian Carlstrombe977852011-07-19 14:54:54 -07001573// Create an array class (i.e. the class object for the array, not the
1574// array itself). "descriptor" looks like "[C" or "[[[[B" or
1575// "[Ljava/lang/String;".
1576//
1577// If "descriptor" refers to an array of primitives, look up the
1578// primitive type's internally-generated class object.
1579//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001580// "class_loader" is the class loader of the class that's referring to
1581// us. It's used to ensure that we're looking for the element type in
1582// the right context. It does NOT become the class loader for the
1583// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001584//
1585// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001586Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001587 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001588
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001589 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001590 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001591 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001592 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001593 return NULL;
1594 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001595
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001596 // See if the component type is already loaded. Array classes are
1597 // always associated with the class loader of their underlying
1598 // element type -- an array of Strings goes with the loader for
1599 // java/lang/String -- so we need to look for it there. (The
1600 // caller should have checked for the existence of the class
1601 // before calling here, but they did so with *their* class loader,
1602 // not the component type's loader.)
1603 //
1604 // If we find it, the caller adds "loader" to the class' initiating
1605 // loader list, which should prevent us from going through this again.
1606 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001607 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001608 // are the same, because our caller (FindClass) just did the
1609 // lookup. (Even if we get this wrong we still have correct behavior,
1610 // because we effectively do this lookup again when we add the new
1611 // class to the hash table --- necessary because of possible races with
1612 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001613 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001614 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001615 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001616 return new_class;
1617 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001618 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001619
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001620 // Fill out the fields in the Class.
1621 //
1622 // It is possible to execute some methods against arrays, because
1623 // all arrays are subclasses of java_lang_Object_, so we need to set
1624 // up a vtable. We can just point at the one in java_lang_Object_.
1625 //
1626 // Array classes are simple enough that we don't need to do a full
1627 // link step.
1628
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001629 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001630 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001631 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001632 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001633 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001634 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001635 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001636 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001637 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001638 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001639 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001640 }
1641 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001642 if (new_class.get() == NULL) {
1643 new_class.reset(AllocClass(sizeof(Class)));
1644 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001645 return NULL;
1646 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001647 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001648 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001649 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001650 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001651 new_class->SetSuperClass(java_lang_Object);
1652 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001653 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001654 new_class->SetClassLoader(component_type->GetClassLoader());
1655 new_class->SetStatus(Class::kStatusInitialized);
1656 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001657 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001658
1659
1660 // All arrays have java/lang/Cloneable and java/io/Serializable as
1661 // interfaces. We need to set that up here, so that stuff like
1662 // "instanceof" works right.
1663 //
1664 // Note: The GC could run during the call to FindSystemClass,
1665 // so we need to make sure the class object is GC-valid while we're in
1666 // there. Do this by clearing the interface list so the GC will just
1667 // think that the entries are null.
1668
1669
1670 // Use the single, global copies of "interfaces" and "iftable"
1671 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001672 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001673 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001674
1675 // Inherit access flags from the component type. Arrays can't be
1676 // used as a superclass or interface, so we want to add "final"
1677 // and remove "interface".
1678 //
1679 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001680 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001681 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001682 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1683 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001684
Ian Rogers5d76c432011-10-31 21:42:49 -07001685 if (InsertClass(descriptor, new_class.get(), false)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001686 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001687 }
1688 // Another thread must have loaded the class after we
1689 // started but before we finished. Abandon what we've
1690 // done.
1691 //
1692 // (Yes, this happens.)
1693
1694 // Grab the winning class.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001695 Class* other_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001696 DCHECK(other_class != NULL);
1697 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001698}
1699
1700Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001701 switch (Primitive::GetType(type)) {
1702 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001703 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001704 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001705 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001706 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001707 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001708 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001709 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001710 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001711 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001712 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001713 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001714 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001715 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001716 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001717 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001718 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001719 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001720 case Primitive::kPrimNot:
1721 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001722 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001723 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001724 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001725 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001726}
1727
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001728bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001729 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001730 DexCache* dex_cache = klass->GetDexCache();
1731 std::string source;
1732 if (dex_cache != NULL) {
1733 source += " from ";
1734 source += dex_cache->GetLocation()->ToModifiedUtf8();
1735 }
1736 LOG(INFO) << "Loaded class " << descriptor << source;
1737 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001738 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001739 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001740 Table::iterator it;
1741 if (image_class) {
1742 // TODO: sanity check there's no match in classes_
1743 it = image_classes_.insert(std::make_pair(hash, klass));
1744 } else {
1745 // TODO: sanity check there's no match in image_classes_
1746 it = classes_.insert(std::make_pair(hash, klass));
1747 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001748 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001749}
1750
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001751bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1752 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001753 MutexLock mu(classes_lock_);
1754 typedef Table::const_iterator It; // TODO: C++0x auto
1755 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001756 ClassHelper kh;
Brian Carlstromae826982011-11-09 01:33:42 -08001757 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
1758 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001759 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001760 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001761 classes_.erase(it);
1762 return true;
1763 }
1764 }
1765 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1766 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001767 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001768 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001769 image_classes_.erase(it);
1770 return true;
1771 }
1772 }
1773 return false;
1774}
1775
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001776Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1777 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001778 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001779 typedef Table::const_iterator It; // TODO: C++0x auto
Ian Rogers5d76c432011-10-31 21:42:49 -07001780 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001781 ClassHelper kh(NULL, this);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001782 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001783 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001784 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001785 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001786 return klass;
1787 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001788 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001789 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1790 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001791 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001792 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001793 return klass;
1794 }
1795 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001796 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001797}
1798
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001799void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001800 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001801 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001802 MutexLock mu(classes_lock_);
1803 typedef Table::const_iterator It; // TODO: C++0x auto
1804 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001805 ClassHelper kh(NULL, this);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001806 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001807 Class* klass = it->second;
1808 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001809 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001810 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001811 }
1812 }
1813 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001814 Class* klass = it->second;
1815 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001816 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001817 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001818 }
1819 }
1820}
1821
jeffhao98eacac2011-09-14 16:11:53 -07001822void ClassLinker::VerifyClass(Class* klass) {
1823 if (klass->IsVerified()) {
1824 return;
1825 }
1826
1827 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001828 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001829
Ian Rogersd81871c2011-10-03 13:57:23 -07001830 if (verifier::DexVerifier::VerifyClass(klass)) {
jeffhao5cfd6fb2011-09-27 13:54:29 -07001831 klass->SetStatus(Class::kStatusVerified);
1832 } else {
1833 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001834 Thread* self = Thread::Current();
1835 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1836 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001837 PrettyDescriptor(klass).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001838 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001839 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001840 }
jeffhao98eacac2011-09-14 16:11:53 -07001841}
1842
Ian Rogersc2b44472011-12-14 21:17:17 -08001843static void CheckProxyConstructor(Method* constructor);
1844static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
1845
Jesse Wilson95caa792011-10-12 18:14:17 -04001846Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001847 ClassLoader* loader, ObjectArray<Method>* methods,
1848 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08001849 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001850 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08001851 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001852 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001853 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001854 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001855 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001856 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07001857 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001858 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08001859
1860 klass->SetStatus(Class::kStatusIdx);
1861
1862 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
1863
1864 // Create static field that holds throws, instance fields are inherited
1865 klass->SetSFields(AllocObjectArray<Field>(1));
1866 SirtRef<Field> sfield(AllocField());
1867 klass->SetStaticField(0, sfield.get());
1868 sfield->SetDexFieldIndex(-1);
1869 sfield->SetDeclaringClass(klass.get());
1870 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001871
Ian Rogers466bb252011-10-14 03:29:56 -07001872 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001873 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001874 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04001875
Ian Rogers466bb252011-10-14 03:29:56 -07001876 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001877 size_t num_virtual_methods = methods->GetLength();
1878 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1879 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001880 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001881 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04001882 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001883
1884 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
1885 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
1886 DCHECK(!Thread::Current()->IsExceptionPending());
1887
1888 // Link the fields and virtual methods, creating vtable and iftables
1889 if (!LinkClass(klass, interfaces)) {
Jesse Wilson95caa792011-10-12 18:14:17 -04001890 DCHECK(Thread::Current()->IsExceptionPending());
1891 return NULL;
1892 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001893 sfield->SetObject(NULL, throws); // initialize throws field
1894 klass->SetStatus(Class::kStatusInitialized);
1895
1896 // sanity checks
1897#ifndef NDEBUG
1898 bool debug = true;
1899#else
1900 bool debug = false;
1901#endif
1902 if (debug) {
1903 CHECK(klass->GetIFields() == NULL);
1904 CheckProxyConstructor(klass->GetDirectMethod(0));
1905 for (size_t i = 0; i < num_virtual_methods; ++i) {
1906 SirtRef<Method> prototype(methods->Get(i));
1907 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
1908 }
Brian Carlstrom89521892011-12-07 22:05:07 -08001909 std::string throws_field_name("java.lang.Class[][] ");
Ian Rogersc2b44472011-12-14 21:17:17 -08001910 throws_field_name += name->ToModifiedUtf8();
1911 throws_field_name += ".throws";
1912 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
1913
1914 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
1915 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
1916 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001917 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04001918}
1919
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001920std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
1921 DCHECK(proxy_class->IsProxyClass());
1922 String* name = proxy_class->GetName();
1923 DCHECK(name != NULL);
1924 return DotToDescriptor(name->ToModifiedUtf8().c_str());
1925}
1926
1927
1928Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07001929 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07001930 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04001931 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07001932 Method* proxy_constructor = proxy_direct_methods->Get(2);
1933 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
1934 // code_ too)
1935 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
1936 // Make this constructor public and fix the class to be our Proxy version
1937 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001938 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08001939 return constructor;
1940}
1941
1942static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07001943 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001944 MethodHelper mh(constructor);
1945 CHECK_STREQ(mh.GetName(), "<init>");
1946 CHECK(mh.GetSignature() == "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07001947 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04001948}
1949
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001950Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
1951 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
1952 // prototype method
1953 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
1954 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07001955 // as necessary
1956 Method* method = down_cast<Method*>(prototype->Clone());
1957
1958 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
1959 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001960 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001961 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001962
Ian Rogers466bb252011-10-14 03:29:56 -07001963 // At runtime the method looks like a reference and argument saving method, clone the code
1964 // related parameters from this method.
1965 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1966 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
1967 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
1968 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
1969 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08001970 return method;
1971}
Jesse Wilson95caa792011-10-12 18:14:17 -04001972
Ian Rogersc2b44472011-12-14 21:17:17 -08001973static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07001974 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001975 CHECK(!prototype->IsFinal());
1976 CHECK(method->IsFinal());
1977 CHECK(!method->IsAbstract());
1978 MethodHelper mh(method);
1979 const char* method_name = mh.GetName();
1980 const char* method_shorty = mh.GetShorty();
1981 Class* method_return = mh.GetReturnType();
1982
1983 mh.ChangeMethod(prototype.get());
1984
1985 CHECK_STREQ(mh.GetName(), method_name);
1986 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07001987
1988 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001989 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04001990}
1991
Brian Carlstrom25c33252011-09-18 15:58:35 -07001992bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001993 CHECK(klass->IsResolved() || klass->IsErroneous())
1994 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001995
Carl Shapirob5573532011-07-12 18:22:59 -07001996 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001997
Brian Carlstrom25c33252011-09-18 15:58:35 -07001998 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001999 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002000 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002001 ObjectLock lock(klass);
2002
Brian Carlstromd1422f82011-09-28 11:37:09 -07002003 if (klass->GetStatus() == Class::kStatusInitialized) {
2004 return true;
2005 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002006
Brian Carlstromd1422f82011-09-28 11:37:09 -07002007 if (klass->IsErroneous()) {
2008 ThrowEarlierClassFailure(klass);
2009 return false;
2010 }
2011
2012 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07002013 VerifyClass(klass);
2014 if (klass->GetStatus() != Class::kStatusVerified) {
Ian Rogers595799e2012-01-11 17:32:51 -08002015 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002016 return false;
2017 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002018 }
2019
Brian Carlstrom25c33252011-09-18 15:58:35 -07002020 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
2021 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002022 // if the class has a <clinit> but we can't run it during compilation,
Ian Rogers595799e2012-01-11 17:32:51 -08002023 // don't bother going to kStatusInitializing. We return true to maintain
2024 // the invariant that a false result implies there is a pending exception.
2025 return true;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002026 }
2027
Brian Carlstromd1422f82011-09-28 11:37:09 -07002028 // If the class is kStatusInitializing, either this thread is
2029 // initializing higher up the stack or another thread has beat us
2030 // to initializing and we need to wait. Either way, this
2031 // invocation of InitializeClass will not be responsible for
2032 // running <clinit> and will return.
2033 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002034 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002035 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002036 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002037 return true;
2038 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002039 // No. That's fine. Wait for another thread to finish initializing.
2040 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002041 }
2042
2043 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers595799e2012-01-11 17:32:51 -08002044 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002045 klass->SetStatus(Class::kStatusError);
2046 return false;
2047 }
2048
Brian Carlstromd1422f82011-09-28 11:37:09 -07002049 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002050
Elliott Hughesdcc24742011-09-07 14:02:44 -07002051 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002052 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002053 }
2054
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002055 uint64_t t0 = NanoTime();
2056
Brian Carlstrom25c33252011-09-18 15:58:35 -07002057 if (!InitializeSuperClass(klass, can_run_clinit)) {
Ian Rogers595799e2012-01-11 17:32:51 -08002058 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002059 return false;
2060 }
2061
2062 InitializeStaticFields(klass);
2063
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002064 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002065 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002066 }
2067
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002068 uint64_t t1 = NanoTime();
2069
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002070 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002071 {
2072 ObjectLock lock(klass);
2073
2074 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002075 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002076 klass->SetStatus(Class::kStatusError);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002077 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002078 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002079 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2080 RuntimeStats* thread_stats = self->GetStats();
2081 ++global_stats->class_init_count;
2082 ++thread_stats->class_init_count;
2083 global_stats->class_init_time_ns += (t1 - t0);
2084 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002085 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002086 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002087 ClassHelper kh(klass);
2088 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002089 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002090 }
2091 lock.NotifyAll();
2092 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002093 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002094}
2095
Brian Carlstromd1422f82011-09-28 11:37:09 -07002096bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
2097 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002098 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002099 lock.Wait();
2100
2101 // When we wake up, repeat the test for init-in-progress. If
2102 // there's an exception pending (only possible if
2103 // "interruptShouldThrow" was set), bail out.
2104 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002105 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002106 klass->SetStatus(Class::kStatusError);
2107 return false;
2108 }
2109 // Spurious wakeup? Go back to waiting.
2110 if (klass->GetStatus() == Class::kStatusInitializing) {
2111 continue;
2112 }
2113 if (klass->IsErroneous()) {
2114 // The caller wants an exception, but it was thrown in a
2115 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002116 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002117 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002118 return false;
2119 }
2120 if (klass->IsInitialized()) {
2121 return true;
2122 }
2123 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2124 }
2125 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2126}
2127
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002128bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2129 if (klass->IsInterface()) {
2130 return true;
2131 }
2132 // begin with the methods local to the superclass
2133 if (klass->HasSuperClass() &&
2134 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2135 const Class* super = klass->GetSuperClass();
Ian Rogers595799e2012-01-11 17:32:51 -08002136 for (int i = super->GetVTable()->GetLength() - 1; i >= 0; --i) {
2137 const Method* method = klass->GetVTable()->Get(i);
2138 if (method != super->GetVTable()->Get(i) &&
2139 !IsSameMethodSignatureInDifferentClassContexts(method, super, klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002140 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2141 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2142 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002143 return false;
2144 }
2145 }
2146 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002147 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2148 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2149 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002150 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2151 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002152 const Method* method = interface_entry->GetMethodArray()->Get(j);
Ian Rogers595799e2012-01-11 17:32:51 -08002153 if (!IsSameMethodSignatureInDifferentClassContexts(method, interface,
2154 method->GetDeclaringClass())) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002155 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2156 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2157 PrettyMethod(method).c_str(),
2158 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002159 return false;
2160 }
2161 }
2162 }
2163 }
2164 return true;
2165}
2166
Ian Rogers595799e2012-01-11 17:32:51 -08002167// Returns true if classes referenced by the signature of the method are the
2168// same classes in klass1 as they are in klass2.
2169bool ClassLinker::IsSameMethodSignatureInDifferentClassContexts(const Method* method,
2170 const Class* klass1,
2171 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002172 if (klass1 == klass2) {
2173 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002174 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002175 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002176 const DexFile::ProtoId& proto_id =
2177 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002178 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2179 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002180 if (descriptor == NULL) {
2181 break;
2182 }
2183 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2184 // Found a non-primitive type.
Ian Rogers595799e2012-01-11 17:32:51 -08002185 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002186 return false;
2187 }
2188 }
2189 }
2190 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002191 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002192 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Ian Rogers595799e2012-01-11 17:32:51 -08002193 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002194 return false;
2195 }
2196 }
2197 return true;
2198}
2199
Ian Rogers595799e2012-01-11 17:32:51 -08002200// Returns true if the descriptor resolves to the same class in the context of klass1 and klass2.
2201bool ClassLinker::IsSameDescriptorInDifferentClassContexts(const char* descriptor,
2202 const Class* klass1,
2203 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002204 CHECK(descriptor != NULL);
2205 CHECK(klass1 != NULL);
2206 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002207 if (klass1 == klass2) {
2208 return true;
2209 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002210 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Ian Rogers595799e2012-01-11 17:32:51 -08002211 if (found1 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002212 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002213 }
Ian Rogers595799e2012-01-11 17:32:51 -08002214 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
2215 if (found2 == NULL) {
2216 Thread::Current()->ClearException();
2217 }
2218 return found1 == found2;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002219}
2220
Brian Carlstrom25c33252011-09-18 15:58:35 -07002221bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002222 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002223 if (!klass->IsInterface() && klass->HasSuperClass()) {
2224 Class* super_class = klass->GetSuperClass();
2225 if (super_class->GetStatus() != Class::kStatusInitialized) {
2226 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002227 Thread* self = Thread::Current();
2228 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002229 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002230 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002231 // TODO: check for a pending exception
2232 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002233 if (!can_run_clinit) {
2234 // Don't set status to error when we can't run <clinit>.
2235 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
2236 klass->SetStatus(Class::kStatusVerified);
2237 return false;
2238 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002239 klass->SetStatus(Class::kStatusError);
2240 klass->NotifyAll();
2241 return false;
2242 }
2243 }
2244 }
2245 return true;
2246}
2247
Brian Carlstrom25c33252011-09-18 15:58:35 -07002248bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002249 CHECK(c != NULL);
2250 if (c->IsInitialized()) {
2251 return true;
2252 }
2253
Elliott Hughes5f791332011-09-15 17:45:30 -07002254 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002255 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Ian Rogers595799e2012-01-11 17:32:51 -08002256 bool success = InitializeClass(c, can_run_clinit);
2257 if (!success) {
2258 CHECK(self->IsExceptionPending());
2259 }
2260 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002261}
2262
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002263void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002264 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002265 const ClassLoader* cl = c->GetClassLoader();
2266 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002267 ClassDataItemIterator it(dex_file, class_data);
2268 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2269 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002270 }
2271}
2272
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002273void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002274 size_t num_static_fields = klass->NumStaticFields();
2275 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002276 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002277 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002278 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002279 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002280 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002281 return;
2282 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002283 ClassHelper kh(klass);
2284 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002285 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002286 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002287 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002288
Ian Rogers0571d352011-11-03 19:51:38 -07002289 if (it.HasNext()) {
2290 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2291 std::map<uint32_t, Field*> field_map;
2292 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2293 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2294 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002295 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002296 }
2297}
2298
Ian Rogersc2b44472011-12-14 21:17:17 -08002299bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002300 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002301 if (!LinkSuperClass(klass)) {
2302 return false;
2303 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002304 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002305 return false;
2306 }
2307 if (!LinkInstanceFields(klass)) {
2308 return false;
2309 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002310 if (!LinkStaticFields(klass)) {
2311 return false;
2312 }
2313 CreateReferenceInstanceOffsets(klass);
2314 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002315 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2316 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002317 return true;
2318}
2319
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002320bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002321 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002322 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2323 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
Ian Rogerscab01012012-01-10 17:35:46 -08002324 CHECK(class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002325 uint16_t super_class_idx = class_def->superclass_idx_;
2326 if (super_class_idx != DexFile::kDexNoIndex16) {
2327 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002328 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002329 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002330 return false;
2331 }
Ian Rogersbe125a92012-01-11 15:19:49 -08002332 // Verify
2333 if (!klass->CanAccess(super_class)) {
2334 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2335 "Class %s extended by class %s is inaccessible",
2336 PrettyDescriptor(super_class).c_str(),
2337 PrettyDescriptor(klass.get()).c_str());
2338 return false;
2339 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002340 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002341 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002342 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2343 if (interfaces != NULL) {
2344 for (size_t i = 0; i < interfaces->Size(); i++) {
2345 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2346 Class* interface = ResolveType(dex_file, idx, klass.get());
2347 if (interface == NULL) {
2348 DCHECK(Thread::Current()->IsExceptionPending());
2349 return false;
2350 }
2351 // Verify
2352 if (!klass->CanAccess(interface)) {
2353 // TODO: the RI seemed to ignore this in my testing.
2354 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2355 "Interface %s implemented by class %s is inaccessible",
2356 PrettyDescriptor(interface).c_str(),
2357 PrettyDescriptor(klass.get()).c_str());
2358 return false;
2359 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002360 }
2361 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002362 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002363 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002364 return true;
2365}
2366
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002367bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002368 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002369 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002370 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002371 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002372 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002373 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002374 return false;
2375 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002376 return true;
2377 }
2378 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002379 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002380 return false;
2381 }
2382 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002383 if (super->IsFinal() || super->IsInterface()) {
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002384 Thread* thread = Thread::Current();
2385 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002386 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002387 PrettyDescriptor(super).c_str(),
2388 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002389 super->IsFinal() ? "declared final" : "an interface");
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002390 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002391 return false;
2392 }
2393 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002394 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002395 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002396 PrettyDescriptor(super).c_str(),
2397 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002398 return false;
2399 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002400
2401 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2402 if (super->IsFinalizable()) {
2403 klass->SetFinalizable();
2404 }
2405
Elliott Hughes2da50362011-10-10 16:57:08 -07002406 // Inherit reference flags (if any) from the superclass.
2407 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2408 if (reference_flags != 0) {
2409 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2410 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002411 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002412 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002413 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002414 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002415 return false;
2416 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002417
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002418#ifndef NDEBUG
2419 // Ensure super classes are fully resolved prior to resolving fields..
2420 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002421 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002422 super = super->GetSuperClass();
2423 }
2424#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002425 return true;
2426}
2427
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002428// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002429bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002430 if (klass->IsInterface()) {
2431 // No vtable.
2432 size_t count = klass->NumVirtualMethods();
2433 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002434 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002435 return false;
2436 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002437 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002438 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002439 }
jeffhaobdb76512011-09-07 11:43:16 -07002440 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002441 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002442 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002443 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002444 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002445 }
2446 return true;
2447}
2448
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002449bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002450 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002451 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2452 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002453 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002454 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002455 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002456 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002457 MethodHelper local_mh(NULL, this);
2458 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002459 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002460 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002461 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002462 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002463 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002464 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002465 super_mh.ChangeMethod(super_method);
2466 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002467 // Verify
2468 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002469 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002470 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002471 PrettyDescriptor(klass.get()).c_str(),
2472 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002473 return false;
2474 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002475 vtable->Set(j, local_method);
2476 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002477 break;
2478 }
2479 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002480 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002481 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002482 vtable->Set(actual_count, local_method);
2483 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002484 actual_count += 1;
2485 }
2486 }
2487 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002488 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002489 return false;
2490 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002491 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002492 CHECK_LE(actual_count, max_count);
2493 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002494 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002495 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002496 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002497 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002498 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002499 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002500 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002501 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002502 return false;
2503 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002504 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002505 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002506 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2507 vtable->Set(i, virtual_method);
2508 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002509 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002510 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002511 }
2512 return true;
2513}
2514
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002515bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002516 size_t super_ifcount;
2517 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002518 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002519 } else {
2520 super_ifcount = 0;
2521 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002522 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002523 ClassHelper kh(klass.get(), this);
2524 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2525 ifcount += num_interfaces;
2526 for (size_t i = 0; i < num_interfaces; i++) {
2527 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2528 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002529 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002530 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002531 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002532 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002533 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002534 return true;
2535 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002536 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002537 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002538 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2539 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogersb52b01a2012-01-12 17:01:38 -08002540 Class* super_interface = super_iftable->Get(i)->GetInterface();
2541 iftable->Set(i, AllocInterfaceEntry(super_interface));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002542 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002543 }
2544 // Flatten the interface inheritance hierarchy.
2545 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002546 for (size_t i = 0; i < num_interfaces; i++) {
2547 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002548 DCHECK(interface != NULL);
2549 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002550 ClassHelper ih(interface);
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002551 Thread* thread = Thread::Current();
2552 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002553 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002554 PrettyDescriptor(klass.get()).c_str(),
2555 PrettyDescriptor(ih.GetDescriptor()).c_str());
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002556 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002557 return false;
2558 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002559 // Check if interface is already in iftable
2560 bool duplicate = false;
2561 for (size_t j = 0; j < idx; j++) {
2562 Class* existing_interface = iftable->Get(j)->GetInterface();
2563 if (existing_interface == interface) {
2564 duplicate = true;
2565 break;
2566 }
2567 }
2568 if (!duplicate) {
2569 // Add this non-duplicate interface.
2570 iftable->Set(idx++, AllocInterfaceEntry(interface));
2571 // Add this interface's non-duplicate super-interfaces.
2572 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2573 Class* super_interface = interface->GetIfTable()->Get(j)->GetInterface();
2574 bool super_duplicate = false;
2575 for (size_t k = 0; k < idx; k++) {
2576 Class* existing_interface = iftable->Get(k)->GetInterface();
2577 if (existing_interface == super_interface) {
2578 super_duplicate = true;
2579 break;
2580 }
2581 }
2582 if (!super_duplicate) {
2583 iftable->Set(idx++, AllocInterfaceEntry(super_interface));
2584 }
2585 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002586 }
2587 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002588 // Shrink iftable in case duplicates were found
2589 if (idx < ifcount) {
2590 iftable.reset(iftable->CopyOf(idx));
2591 ifcount = idx;
2592 } else {
2593 CHECK_EQ(idx, ifcount);
2594 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002595 klass->SetIfTable(iftable.get());
Elliott Hughes4681c802011-09-25 18:04:37 -07002596
2597 // If we're an interface, we don't need the vtable pointers, so we're done.
2598 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002599 return true;
2600 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002601 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002602 MethodHelper vtable_mh(NULL, this);
2603 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002604 for (size_t i = 0; i < ifcount; ++i) {
2605 InterfaceEntry* interface_entry = iftable->Get(i);
2606 Class* interface = interface_entry->GetInterface();
2607 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2608 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002609 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002610 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2611 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002612 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002613 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002614 // For each method listed in the interface's method list, find the
2615 // matching method in our class's method list. We want to favor the
2616 // subclass over the superclass, which just requires walking
2617 // back from the end of the vtable. (This only matters if the
2618 // superclass defines a private method and this class redefines
2619 // it -- otherwise it would use the same vtable slot. In .dex files
2620 // those don't end up in the virtual method table, so it shouldn't
2621 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002622 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2623 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002624 vtable_mh.ChangeMethod(vtable_method);
2625 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002626 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002627 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002628 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002629 return false;
2630 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002631 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002632 break;
2633 }
2634 }
2635 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002636 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002637 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002638 Method* mir_method = miranda_list[mir];
2639 vtable_mh.ChangeMethod(mir_method);
2640 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002641 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002642 break;
2643 }
2644 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002645 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002646 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002647 miranda_method.reset(AllocMethod());
2648 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2649 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002650 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002651 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002652 }
2653 }
2654 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002655 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002656 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002657 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002658 klass->SetVirtualMethods((old_method_count == 0)
2659 ? AllocObjectArray<Method>(new_method_count)
2660 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002661
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002662 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2663 CHECK(vtable != NULL);
2664 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002665 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002666 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002667 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002668 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002669 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002670 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2671 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2672 klass->SetVirtualMethod(old_method_count + i, method);
2673 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002674 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002675 // TODO: do not assign to the vtable field until it is fully constructed.
2676 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002677 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002678
2679 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2680 for (int i = 0; i < vtable->GetLength(); ++i) {
2681 CHECK(vtable->Get(i) != NULL);
2682 }
2683
2684// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2685
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002686 return true;
2687}
2688
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002689bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2690 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002691 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002692}
2693
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002694bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2695 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002696 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002697 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002698 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002699 return success;
2700}
2701
Brian Carlstromdbc05252011-09-09 01:59:59 -07002702struct LinkFieldsComparator {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002703 LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002704 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002705 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002706 fh_->ChangeField(field1);
2707 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2708 fh_->ChangeField(field2);
2709 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002710 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2711 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2712 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2713 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002714 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2715 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2716 if (order1 != order2) {
2717 return order1 < order2;
2718 }
2719
2720 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002721 fh_->ChangeField(field1);
2722 StringPiece name1(fh_->GetName());
2723 fh_->ChangeField(field2);
2724 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002725 return name1 < name2;
2726 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002727
2728 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002729};
2730
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002731bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002732 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002733 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002734
2735 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002736 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002737
2738 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002739 size_t size;
2740 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002741 if (is_static) {
2742 size = klass->GetClassSize();
2743 field_offset = Class::FieldsOffset();
2744 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002745 Class* super_class = klass->GetSuperClass();
2746 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002747 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002748 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002749 }
2750 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002751 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002752
Brian Carlstromdbc05252011-09-09 01:59:59 -07002753 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002754
Brian Carlstromdbc05252011-09-09 01:59:59 -07002755 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002756 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002757 std::deque<Field*> grouped_and_sorted_fields;
2758 for (size_t i = 0; i < num_fields; i++) {
2759 grouped_and_sorted_fields.push_back(fields->Get(i));
2760 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002761 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002762 std::sort(grouped_and_sorted_fields.begin(),
2763 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002764 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002765
2766 // References should be at the front.
2767 size_t current_field = 0;
2768 size_t num_reference_fields = 0;
2769 for (; current_field < num_fields; current_field++) {
2770 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002771 fh.ChangeField(field);
2772 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002773 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002774 if (isPrimitive) {
2775 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002776 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002777 grouped_and_sorted_fields.pop_front();
2778 num_reference_fields++;
2779 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002780 field->SetOffset(field_offset);
2781 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002782 }
2783
2784 // Now we want to pack all of the double-wide fields together. If
2785 // we're not aligned, though, we want to shuffle one 32-bit field
2786 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002787 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002788 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2789 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002790 fh.ChangeField(field);
2791 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002792 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2793 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002794 continue;
2795 }
2796 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002797 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002798 // drop the consumed field
2799 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2800 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002801 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002802 // whether we found a 32-bit field for padding or not, we advance
2803 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002804 }
2805
2806 // Alignment is good, shuffle any double-wide fields forward, and
2807 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002808 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002809 while (!grouped_and_sorted_fields.empty()) {
2810 Field* field = grouped_and_sorted_fields.front();
2811 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002812 fh.ChangeField(field);
2813 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002814 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002815 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002816 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002817 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002818 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002819 ? sizeof(uint64_t)
2820 : sizeof(uint32_t)));
2821 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002822 }
2823
Elliott Hughesadb460d2011-10-05 17:02:34 -07002824 // 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 -08002825 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
2826 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002827 // We know there are no non-reference fields in the Reference classes, and we know
2828 // that 'referent' is alphabetically last, so this is easy...
2829 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002830 fh.ChangeField(fields->Get(num_fields - 1));
2831 StringPiece name(fh.GetName());
2832 CHECK(name == "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07002833 --num_reference_fields;
2834 }
2835
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002836#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002837 // Make sure that all reference fields appear before
2838 // non-reference fields, and all double-wide fields are aligned.
2839 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002840 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002841 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002842 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002843 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002844 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002845 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002846 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2847 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002848 fh.ChangeField(field);
2849 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002850 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002851 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002852 is_primitive = true; // We lied above, so we have to expect a lie here.
2853 }
2854 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002855 if (!seen_non_ref) {
2856 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002857 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002858 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002859 } else {
2860 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002861 }
2862 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002863 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002864 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002865 }
2866#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002867 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002868 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002869 if (is_static) {
2870 klass->SetNumReferenceStaticFields(num_reference_fields);
2871 klass->SetClassSize(size);
2872 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002873 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002874 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002875 klass->SetObjectSize(size);
2876 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002877 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002878 return true;
2879}
2880
2881// Set the bitmap of reference offsets, refOffsets, from the ifields
2882// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002883void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002884 uint32_t reference_offsets = 0;
2885 Class* super_class = klass->GetSuperClass();
2886 if (super_class != NULL) {
2887 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002888 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002889 if (reference_offsets == CLASS_WALK_SUPER) {
2890 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002891 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002892 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002893 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002894 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002895}
2896
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002897void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002898 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002899}
2900
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002901void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002902 uint32_t reference_offsets) {
2903 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002904 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2905 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002906 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002907 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002908 // All of the fields that contain object references are guaranteed
2909 // to be at the beginning of the fields list.
2910 for (size_t i = 0; i < num_reference_fields; ++i) {
2911 // Note that byte_offset is the offset from the beginning of
2912 // object, not the offset into instance data
2913 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002914 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002915 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2916 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2917 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002918 CHECK_NE(new_bit, 0U);
2919 reference_offsets |= new_bit;
2920 } else {
2921 reference_offsets = CLASS_WALK_SUPER;
2922 break;
2923 }
2924 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002925 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002926 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002927 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002928 } else {
2929 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002930 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002931}
2932
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002933String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002934 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002935 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002936 if (resolved != NULL) {
2937 return resolved;
2938 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002939 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2940 int32_t utf16_length = dex_file.GetStringLength(string_id);
2941 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002942 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002943 dex_cache->SetResolvedString(string_idx, string);
2944 return string;
2945}
2946
2947Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002948 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002949 DexCache* dex_cache,
2950 const ClassLoader* class_loader) {
2951 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002952 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07002953 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002954 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002955 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05002956 // TODO: we used to throw here if resolved's class loader was not the
2957 // boot class loader. This was to permit different classes with the
2958 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002959 dex_cache->SetResolvedType(type_idx, resolved);
2960 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08002961 CHECK(Thread::Current()->IsExceptionPending())
2962 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002963 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002964 }
2965 return resolved;
2966}
2967
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002968Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2969 uint32_t method_idx,
2970 DexCache* dex_cache,
2971 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002972 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002973 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2974 if (resolved != NULL) {
2975 return resolved;
2976 }
2977 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2978 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2979 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002980 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002981 return NULL;
2982 }
2983
Ian Rogers0571d352011-11-03 19:51:38 -07002984 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
2985 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002986 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002987 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002988 } else if (klass->IsInterface()) {
2989 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002990 } else {
2991 resolved = klass->FindVirtualMethod(name, signature);
2992 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002993 if (resolved != NULL) {
2994 dex_cache->SetResolvedMethod(method_idx, resolved);
2995 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002996 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002997 }
2998 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002999}
3000
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003001Field* ClassLinker::ResolveField(const DexFile& dex_file,
3002 uint32_t field_idx,
3003 DexCache* dex_cache,
3004 const ClassLoader* class_loader,
3005 bool is_static) {
3006 Field* resolved = dex_cache->GetResolvedField(field_idx);
3007 if (resolved != NULL) {
3008 return resolved;
3009 }
3010 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3011 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3012 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003013 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003014 return NULL;
3015 }
3016
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003017 const char* name = dex_file.GetFieldName(field_id);
3018 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003019 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003020 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003021 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003022 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003023 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003024 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003025 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003026 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08003027 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
3028 }
3029 return resolved;
3030}
3031
3032Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
3033 uint32_t field_idx,
3034 DexCache* dex_cache,
3035 const ClassLoader* class_loader) {
3036 Field* resolved = dex_cache->GetResolvedField(field_idx);
3037 if (resolved != NULL) {
3038 return resolved;
3039 }
3040 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3041 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3042 if (klass == NULL) {
3043 DCHECK(Thread::Current()->IsExceptionPending());
3044 return NULL;
3045 }
3046
3047 const char* name = dex_file.GetFieldName(field_id);
3048 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3049 resolved = klass->FindField(name, type);
3050 if (resolved != NULL) {
3051 dex_cache->SetResolvedField(field_idx, resolved);
3052 } else {
3053 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003054 }
3055 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07003056}
3057
Ian Rogersad25ac52011-10-04 19:13:33 -07003058const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
3059 Class* declaring_class = referrer->GetDeclaringClass();
3060 DexCache* dex_cache = declaring_class->GetDexCache();
3061 const DexFile& dex_file = FindDexFile(dex_cache);
3062 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3063 return dex_file.GetShorty(method_id.proto_idx_);
3064}
3065
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003066void ClassLinker::DumpAllClasses(int flags) const {
3067 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3068 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3069 std::vector<Class*> all_classes;
3070 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003071 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003072 typedef Table::const_iterator It; // TODO: C++0x auto
3073 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3074 all_classes.push_back(it->second);
3075 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003076 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3077 all_classes.push_back(it->second);
3078 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003079 }
3080
3081 for (size_t i = 0; i < all_classes.size(); ++i) {
3082 all_classes[i]->DumpClass(std::cerr, flags);
3083 }
3084}
3085
Elliott Hughescac6cc72011-11-03 20:31:21 -07003086void ClassLinker::DumpForSigQuit(std::ostream& os) const {
3087 MutexLock mu(classes_lock_);
3088 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3089 << classes_.size() << " allocated classes\n";
3090}
3091
Elliott Hughese27955c2011-08-26 15:21:24 -07003092size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003093 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003094 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003095}
3096
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003097pid_t ClassLinker::GetClassesLockOwner() {
3098 return classes_lock_.GetOwner();
3099}
3100
3101pid_t ClassLinker::GetDexLockOwner() {
3102 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003103}
3104
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003105void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3106 DCHECK(!init_done_);
3107
3108 DCHECK(klass != NULL);
3109 DCHECK(klass->GetClassLoader() == NULL);
3110
3111 DCHECK(class_roots_ != NULL);
3112 DCHECK(class_roots_->Get(class_root) == NULL);
3113 class_roots_->Set(class_root, klass);
3114}
3115
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003116} // namespace art