blob: 5687453448ef403780c1881433a9bd9d07363cf5 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Brian Carlstromd601af82012-01-06 10:15:19 -080019#include <fcntl.h>
20#include <sys/file.h>
21#include <sys/stat.h>
Brian Carlstromdbf05b72011-12-15 00:55:24 -080022#include <sys/types.h>
23#include <sys/wait.h>
24
Brian Carlstromdbc05252011-09-09 01:59:59 -070025#include <deque>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070026#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070027#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070028#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070029
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070030#include "casts.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070031#include "class_loader.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080032#include "debugger.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070033#include "dex_cache.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070034#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070035#include "dex_verifier.h"
36#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070037#include "intern_table.h"
Ian Rogers0571d352011-11-03 19:51:38 -070038#include "leb128.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070039#include "logging.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070040#include "oat_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070041#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080042#include "object_utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070043#include "runtime.h"
Ian Rogers466bb252011-10-14 03:29:56 -070044#include "runtime_support.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070045#include "ScopedLocalRef.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070046#include "space.h"
Brian Carlstrom40381fb2011-10-19 14:13:40 -070047#include "stack_indirect_reference_table.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070048#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070049#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070050#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070051#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070052
53namespace art {
54
Elliott Hughes4a2b4172011-09-20 17:08:25 -070055namespace {
56
Elliott Hughes362f9bc2011-10-17 18:56:41 -070057void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070058void ThrowNoClassDefFoundError(const char* fmt, ...) {
59 va_list args;
60 va_start(args, fmt);
61 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
62 va_end(args);
63}
64
Elliott Hughes362f9bc2011-10-17 18:56:41 -070065void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughese555dc02011-09-25 10:46:35 -070066void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070067 va_list args;
68 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070069 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070070 va_end(args);
71}
72
Elliott Hughes362f9bc2011-10-17 18:56:41 -070073void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070074void ThrowLinkageError(const char* fmt, ...) {
75 va_list args;
76 va_start(args, fmt);
77 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
78 va_end(args);
79}
80
Ian Rogers9f1ab122011-12-12 08:52:43 -080081void ThrowNoSuchMethodError(bool is_direct, Class* c, const StringPiece& name,
82 const StringPiece& signature) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080083 ClassHelper kh(c);
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070084 std::ostringstream msg;
Ian Rogers9f1ab122011-12-12 08:52:43 -080085 msg << "no " << (is_direct ? "direct" : "virtual") << " method " << name << "." << signature
86 << " in class " << kh.GetDescriptor() << " or its superclasses";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080087 std::string location(kh.GetLocation());
88 if (!location.empty()) {
89 msg << " (defined in " << location << ")";
Elliott Hughescc5f9a92011-09-28 19:17:29 -070090 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070091 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070092}
93
Ian Rogersb067ac22011-12-13 18:05:09 -080094void ThrowNoSuchFieldError(const StringPiece& scope, Class* c, const StringPiece& type,
Ian Rogers9f1ab122011-12-12 08:52:43 -080095 const StringPiece& name) {
96 ClassHelper kh(c);
97 std::ostringstream msg;
Ian Rogersb067ac22011-12-13 18:05:09 -080098 msg << "no " << scope << "field " << name << " of type " << type
Ian Rogers9f1ab122011-12-12 08:52:43 -080099 << " in class " << kh.GetDescriptor() << " or its superclasses";
100 std::string location(kh.GetLocation());
101 if (!location.empty()) {
102 msg << " (defined in " << location << ")";
103 }
104 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchFieldError;", msg.str().c_str());
105}
106
Ian Rogerscab01012012-01-10 17:35:46 -0800107void ThrowNullPointerException(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
108void ThrowNullPointerException(const char* fmt, ...) {
109 va_list args;
110 va_start(args, fmt);
111 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NullPointerException;", fmt, args);
112 va_end(args);
113}
114
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700115void ThrowEarlierClassFailure(Class* c) {
116 /*
117 * The class failed to initialize on a previous attempt, so we want to throw
118 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
119 * failed in verification, in which case v2 5.4.1 says we need to re-throw
120 * the previous error.
121 */
122 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
123
Brian Carlstrom4d9716c2012-01-30 01:49:33 -0800124 CHECK(c->IsErroneous()) << PrettyClass(c);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700125 if (c->GetVerifyErrorClass() != NULL) {
126 // TODO: change the verifier to store an _instance_, with a useful detail message?
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800127 ClassHelper ve_ch(c->GetVerifyErrorClass());
128 std::string error_descriptor(ve_ch.GetDescriptor());
129 Thread::Current()->ThrowNewException(error_descriptor.c_str(), PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700130 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800131 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700132 }
133}
134
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700135void WrapExceptionInInitializer() {
136 JNIEnv* env = Thread::Current()->GetJniEnv();
137
138 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
139 CHECK(cause.get() != NULL);
140
141 env->ExceptionClear();
142
143 // TODO: add java.lang.Error to JniConstants?
144 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
145 CHECK(error_class.get() != NULL);
146 if (env->IsInstanceOf(cause.get(), error_class.get())) {
147 // We only wrap non-Error exceptions; an Error can just be used as-is.
148 env->Throw(cause.get());
149 return;
150 }
151
152 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
153 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
154 CHECK(eiie_class.get() != NULL);
155
156 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
157 CHECK(mid != NULL);
158
159 ScopedLocalRef<jthrowable> eiie(env,
160 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
161 env->Throw(eiie.get());
162}
163
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800164static size_t Hash(const char* s) {
165 // This is the java.lang.String hashcode for convenience, not interoperability.
166 size_t hash = 0;
167 for (; *s != '\0'; ++s) {
168 hash = hash * 31 + *s;
169 }
170 return hash;
171}
172
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700173} // namespace
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700174
Elliott Hughes418d20f2011-09-22 14:00:39 -0700175const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700176 "Ljava/lang/Class;",
177 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700178 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700179 "[Ljava/lang/Object;",
180 "Ljava/lang/String;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700181 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700182 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700183 "Ljava/lang/reflect/Field;",
184 "Ljava/lang/reflect/Method;",
Ian Rogers466bb252011-10-14 03:29:56 -0700185 "Ljava/lang/reflect/Proxy;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700186 "Ljava/lang/ClassLoader;",
187 "Ldalvik/system/BaseDexClassLoader;",
188 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700189 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700190 "Z",
191 "B",
192 "C",
193 "D",
194 "F",
195 "I",
196 "J",
197 "S",
198 "V",
199 "[Z",
200 "[B",
201 "[C",
202 "[D",
203 "[F",
204 "[I",
205 "[J",
206 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700207 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700208};
209
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800210ClassLinker* ClassLinker::Create(const std::string& boot_class_path, InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700211 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800212 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700213 class_linker->Init(boot_class_path);
214 return class_linker.release();
215}
216
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800217ClassLinker* ClassLinker::Create(InternTable* intern_table) {
218 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700219 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700220 return class_linker.release();
221}
222
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800223ClassLinker::ClassLinker(InternTable* intern_table)
224 : dex_lock_("ClassLinker dex lock"),
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700225 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700226 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700227 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700228 init_done_(false),
229 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700230 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700231}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700232
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700233void CreateClassPath(const std::string& class_path,
234 std::vector<const DexFile*>& class_path_vector) {
235 std::vector<std::string> parsed;
236 Split(class_path, ':', parsed);
237 for (size_t i = 0; i < parsed.size(); ++i) {
238 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700239 if (dex_file == NULL) {
240 LOG(WARNING) << "Failed to open dex file " << parsed[i];
241 } else {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700242 class_path_vector.push_back(dex_file);
243 }
244 }
245}
246
247void ClassLinker::Init(const std::string& boot_class_path) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800248 VLOG(startup) << "ClassLinker::InitFrom entering boot_class_path=" << boot_class_path;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700249
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700250 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700251
Elliott Hughes30646832011-10-13 16:59:46 -0700252 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700253 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
254 CHECK(java_lang_Class.get() != NULL);
255 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700256 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700257 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700258
Elliott Hughes418d20f2011-09-22 14:00:39 -0700259 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700260 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
261 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700262
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700263 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700264 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
265 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700266 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700267 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700268 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700269
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700270 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700271 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
272 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700273
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700274 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700275 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700276
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700277 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700278 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
279 char_array_class->SetComponentType(char_class.get());
280 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700281
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700282 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700283 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
284 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700285 java_lang_String->SetObjectSize(sizeof(String));
286 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400287
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700288 // Create storage for root classes, save away our work so far (requires
289 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700290 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700291 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700292 SetClassRoot(kJavaLangClass, java_lang_Class.get());
293 SetClassRoot(kJavaLangObject, java_lang_Object.get());
294 SetClassRoot(kClassArrayClass, class_array_class.get());
295 SetClassRoot(kObjectArrayClass, object_array_class.get());
296 SetClassRoot(kCharArrayClass, char_array_class.get());
297 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700298
299 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700300 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
301 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
302 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
303 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
304 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
305 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
306 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
307 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700308
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700309 // Create array interface entries to populate once we can load system classes
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700310 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700311
312 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700313 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700314 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700315 IntArray::SetArrayClass(int_array_class.get());
316 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700317
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700318 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700319
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700320 // setup boot_class_path_ and register class_path now that we can
321 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700322 std::vector<const DexFile*> boot_class_path_vector;
323 CreateClassPath(boot_class_path, boot_class_path_vector);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700324 CHECK_NE(0U, boot_class_path_vector.size());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700325 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
326 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700327 CHECK(dex_file != NULL);
328 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700329 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700330
Elliott Hughes80609252011-09-23 17:24:51 -0700331 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700332 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700333 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700334 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700335 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700336 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
337
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700338 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
339 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700340 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700341 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700342 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700343 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700344
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700345 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700346 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700347 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700348 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700349 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700350 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700351
352 // now we can use FindSystemClass
353
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700354 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700355 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700356 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700357
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700358 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700359 java_lang_Object->SetStatus(Class::kStatusNotReady);
360 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700361 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700362 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
363 java_lang_String->SetStatus(Class::kStatusNotReady);
364 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700365 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700366 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
367
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700368 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700369 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
370 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
371
372 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
373 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
374
375 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700376 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700377
378 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
379 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
380
381 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700382 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700383
384 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
385 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
386
387 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
388 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
389
390 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
391 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
392
Elliott Hughes418d20f2011-09-22 14:00:39 -0700393 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700394 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700395
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700396 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700397 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700398
399 // Setup the single, global copies of "interfaces" and "iftable"
400 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
401 CHECK(java_lang_Cloneable != NULL);
402 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
403 CHECK(java_io_Serializable != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700404 // We assume that Cloneable/Serializable don't have superinterfaces --
405 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700406 // supers as well.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800407 array_iftable_->Set(0, AllocInterfaceEntry(java_lang_Cloneable));
408 array_iftable_->Set(1, AllocInterfaceEntry(java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700409
Elliott Hughes418d20f2011-09-22 14:00:39 -0700410 // Sanity check Class[] and Object[]'s interfaces
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800411 ClassHelper kh(class_array_class.get(), this);
412 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
413 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
414 kh.ChangeClass(object_array_class.get());
415 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
416 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
Elliott Hughes80609252011-09-23 17:24:51 -0700417 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700418 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700419 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700420 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700421
Elliott Hughes80609252011-09-23 17:24:51 -0700422 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
423 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700424 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700425
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700426 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700427 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700428 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700429
430 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700431 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700432 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700433
Ian Rogers466bb252011-10-14 03:29:56 -0700434 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
435
436 // Create java.lang.reflect.Proxy root
437 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
438 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
439
Brian Carlstrom1f870082011-08-23 16:02:11 -0700440 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700441 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
442 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700443 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700444 java_lang_ref_FinalizerReference->SetAccessFlags(
445 java_lang_ref_FinalizerReference->GetAccessFlags() |
446 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700447 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700448 java_lang_ref_PhantomReference->SetAccessFlags(
449 java_lang_ref_PhantomReference->GetAccessFlags() |
450 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700451 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700452 java_lang_ref_SoftReference->SetAccessFlags(
453 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700454 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700455 java_lang_ref_WeakReference->SetAccessFlags(
456 java_lang_ref_WeakReference->GetAccessFlags() |
457 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700458
Brian Carlstromaded5f72011-10-07 17:15:04 -0700459 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700460 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700461 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700462 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
463
464 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
465 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
466 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
467
468 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
469 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
470 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
471 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
472
473 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700474 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
475 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700476 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700477
Brian Carlstroma663ea52011-08-19 23:33:41 -0700478 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700479
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800480 VLOG(startup) << "ClassLinker::InitFrom exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700481}
482
483void ClassLinker::FinishInit() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800484 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700485
486 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700487 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700488 // as the types of the field can't be resolved prior to the runtime being
489 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700490 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700491 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700492 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
493
Elliott Hughesadb460d2011-10-05 17:02:34 -0700494 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
495
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800496 const DexFile& java_lang_dex = FindDexFile(java_lang_ref_Reference->GetDexCache());
497
Brian Carlstrom16192862011-09-12 17:50:06 -0700498 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800499 FieldHelper fh(pendingNext, this);
500 CHECK_STREQ(fh.GetName(), "pendingNext");
501 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
502 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700503
504 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800505 fh.ChangeField(queue);
506 CHECK_STREQ(fh.GetName(), "queue");
507 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
508 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700509
510 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800511 fh.ChangeField(queueNext);
512 CHECK_STREQ(fh.GetName(), "queueNext");
513 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
514 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700515
516 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800517 fh.ChangeField(referent);
518 CHECK_STREQ(fh.GetName(), "referent");
519 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
520 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700521
522 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800523 fh.ChangeField(zombie);
524 CHECK_STREQ(fh.GetName(), "zombie");
525 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
526 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700527
528 Heap::SetReferenceOffsets(referent->GetOffset(),
529 queue->GetOffset(),
530 queueNext->GetOffset(),
531 pendingNext->GetOffset(),
532 zombie->GetOffset());
533
Brian Carlstroma663ea52011-08-19 23:33:41 -0700534 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700535 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700536 ClassRoot class_root = static_cast<ClassRoot>(i);
537 Class* klass = GetClassRoot(class_root);
538 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700539 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700540 // note SetClassRoot does additional validation.
541 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700542 }
543
Elliott Hughes92f14b22011-10-06 12:29:54 -0700544 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700545
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700546 // disable the slow paths in FindClass and CreatePrimitiveClass now
547 // that Object, Class, and Object[] are setup
548 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700549
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800550 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700551}
552
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700553void ClassLinker::RunRootClinits() {
554 Thread* self = Thread::Current();
555 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
556 Class* c = GetClassRoot(ClassRoot(i));
557 if (!c->IsArrayClass() && !c->IsPrimitive()) {
558 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700559 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700560 }
561 }
562}
563
Brian Carlstromd601af82012-01-06 10:15:19 -0800564bool ClassLinker::GenerateOatFile(const std::string& dex_filename,
565 int oat_fd,
566 const std::string& oat_cache_filename) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800567 std::string dex2oat_string("/system/bin/dex2oat");
568#ifndef NDEBUG
569 dex2oat_string += 'd';
570#endif
571 const char* dex2oat = dex2oat_string.c_str();
572
573 const char* class_path = Runtime::Current()->GetClassPath().c_str();
574
575 std::string boot_image_option_string("--boot-image=");
Ian Rogers30fab402012-01-23 15:43:46 -0800576 boot_image_option_string += Heap::GetSpaces()[0]->AsImageSpace()->GetImageFilename();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800577 const char* boot_image_option = boot_image_option_string.c_str();
578
579 std::string dex_file_option_string("--dex-file=");
Brian Carlstromd601af82012-01-06 10:15:19 -0800580 dex_file_option_string += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800581 const char* dex_file_option = dex_file_option_string.c_str();
582
Brian Carlstromd601af82012-01-06 10:15:19 -0800583 std::string oat_fd_option_string("--oat-fd=");
Brian Carlstrom866c8622012-01-06 16:35:13 -0800584 StringAppendF(&oat_fd_option_string, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800585 const char* oat_fd_option = oat_fd_option_string.c_str();
586
587 std::string oat_name_option_string("--oat-name=");
588 oat_name_option_string += oat_cache_filename;
589 const char* oat_name_option = oat_name_option_string.c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800590
jeffhao262bf462011-10-20 18:36:32 -0700591 // fork and exec dex2oat
592 pid_t pid = fork();
593 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800594 // no allocation allowed between fork and exec
Ian Rogers725aee52012-01-11 11:56:56 -0800595
596 // change process groups, so we don't get reaped by ProcessManager
597 setpgid(0, 0);
598
jeffhao10037c82012-01-23 15:06:23 -0800599 VLOG(class_linker) << dex2oat
600 << " --runtime-arg -Xms64m"
601 << " --runtime-arg -Xmx64m"
602 << " --runtime-arg -classpath"
603 << " --runtime-arg " << class_path
604 << " " << boot_image_option
605 << " " << dex_file_option
606 << " " << oat_fd_option
607 << " " << oat_name_option;
608
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800609 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700610 "--runtime-arg", "-Xms64m",
611 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500612 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800613 "--runtime-arg", class_path,
614 boot_image_option,
615 dex_file_option,
Brian Carlstromd601af82012-01-06 10:15:19 -0800616 oat_fd_option,
617 oat_name_option,
jeffhao262bf462011-10-20 18:36:32 -0700618 NULL);
619
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800620 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
Brian Carlstromd601af82012-01-06 10:15:19 -0800621 return false;
jeffhao262bf462011-10-20 18:36:32 -0700622 } else {
623 // wait for dex2oat to finish
624 int status;
625 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
626 if (got_pid != pid) {
627 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
Brian Carlstromd601af82012-01-06 10:15:19 -0800628 return false;
jeffhao262bf462011-10-20 18:36:32 -0700629 }
630 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800631 LOG(ERROR) << dex2oat << " failed with dex-file=" << dex_filename;
632 return false;
jeffhao262bf462011-10-20 18:36:32 -0700633 }
634 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800635 return true;
jeffhao262bf462011-10-20 18:36:32 -0700636}
637
Brian Carlstrom866c8622012-01-06 16:35:13 -0800638void ClassLinker::RegisterOatFile(const OatFile& oat_file) {
639 MutexLock mu(dex_lock_);
640 RegisterOatFileLocked(oat_file);
641}
642
643void ClassLinker::RegisterOatFileLocked(const OatFile& oat_file) {
644 dex_lock_.AssertHeld();
645 oat_files_.push_back(&oat_file);
646}
647
Ian Rogers30fab402012-01-23 15:43:46 -0800648OatFile* ClassLinker::OpenOat(const ImageSpace* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700649 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700650 const Runtime* runtime = Runtime::Current();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700651 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800652 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
653 // check the down cast
654 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700655 std::string oat_filename;
656 oat_filename += runtime->GetHostPrefix();
657 oat_filename += oat_location->ToModifiedUtf8();
Ian Rogers30fab402012-01-23 15:43:46 -0800658 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBegin());
659 VLOG(startup) << "ClassLinker::OpenOat entering oat_filename=" << oat_filename;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700660 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700661 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700662 return NULL;
663 }
664 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
665 uint32_t image_oat_checksum = image_header.GetOatChecksum();
666 if (oat_checksum != image_oat_checksum) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800667 LOG(ERROR) << "Failed to match oat file checksum " << std::hex << oat_checksum
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700668 << " to expected oat checksum " << std::hex << oat_checksum
669 << " in image";
670 return NULL;
671 }
Brian Carlstrom866c8622012-01-06 16:35:13 -0800672 RegisterOatFileLocked(*oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800673 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700674 return oat_file;
675}
676
Brian Carlstromae826982011-11-09 01:33:42 -0800677const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
678 for (size_t i = 0; i < oat_files_.size(); i++) {
679 const OatFile* oat_file = oat_files_[i];
680 DCHECK(oat_file != NULL);
Ian Rogers7fe2c692011-12-06 16:35:59 -0800681 if (oat_file->GetOatDexFile(dex_file.GetLocation(), false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800682 return oat_file;
683 }
684 }
685 return NULL;
686}
687
Brian Carlstromd601af82012-01-06 10:15:19 -0800688class LockedFd {
689 public:
690 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
691 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
692 if (fd == -1) {
693 PLOG(ERROR) << "Failed to open file '" << name << "'";
694 return NULL;
695 }
696 fchmod(fd, mode);
697
698 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
699 // try to lock non-blocking so we can log if we need may need to block
700 int result = flock(fd, LOCK_EX | LOCK_NB);
701 if (result == -1) {
702 LOG(WARNING) << "sleeping while locking file " << name;
703 // retry blocking
704 result = flock(fd, LOCK_EX);
705 }
706 if (result == -1) {
707 PLOG(ERROR) << "Failed to lock file '" << name << "'";
708 close(fd);
709 return NULL;
710 }
711 return new LockedFd(fd);
712 }
713
714 int GetFd() const {
715 return fd_;
716 }
717
718 ~LockedFd() {
719 if (fd_ != -1) {
720 int result = flock(fd_, LOCK_UN);
721 if (result == -1) {
722 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
723 }
724 close(fd_);
725 }
726 }
727
728 private:
729 explicit LockedFd(int fd) : fd_(fd) {}
730
731 int fd_;
732};
733
Brian Carlstromae826982011-11-09 01:33:42 -0800734const OatFile* ClassLinker::FindOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700735 MutexLock mu(dex_lock_);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800736 const OatFile* open_oat_file = FindOpenedOatFileForDexFile(dex_file);
737 if (open_oat_file != NULL) {
738 return open_oat_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800739 }
740
Brian Carlstromd601af82012-01-06 10:15:19 -0800741 std::string oat_filename(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
Brian Carlstrom866c8622012-01-06 16:35:13 -0800742 open_oat_file = FindOpenedOatFileFromOatLocation(oat_filename);
743 if (open_oat_file != NULL) {
744 return open_oat_file;
745 }
746
Brian Carlstromd601af82012-01-06 10:15:19 -0800747 while (true) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800748 UniquePtr<const OatFile> oat_file(FindOatFileFromOatLocation(oat_filename));
749 if (oat_file.get() != NULL) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800750 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
751 if (dex_file.GetHeader().checksum_ == oat_dex_file->GetDexFileChecksum()) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800752 RegisterOatFileLocked(*oat_file.get());
753 return oat_file.release();
Brian Carlstromd601af82012-01-06 10:15:19 -0800754 }
755 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
756 << " checksum mismatch with " << dex_file.GetLocation() << " --- regenerating";
757 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
758 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
759 }
760 // Fall through...
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700761 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800762 // Try to generate oat file if it wasn't found or was obsolete.
763 // Note we can be racing with another runtime to do this.
764 std::string oat_cache_filename(GetArtCacheFilenameOrDie(oat_filename));
765 UniquePtr<LockedFd> locked_fd(LockedFd::CreateAndLock(oat_cache_filename, 0644));
766 if (locked_fd.get() == NULL) {
767 LOG(ERROR) << "Failed to create and lock oat file " << oat_cache_filename;
768 return NULL;
Elliott Hughes234da572011-11-03 22:13:06 -0700769 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800770 // Check to see if the fd we opened and locked matches the file in
771 // the filesystem. If they don't, then somebody else unlinked ours
772 // and created a new file, and we need to use that one instead. (If
773 // we caught them between the unlink and the create, we'll get an
774 // ENOENT from the file stat.)
775 struct stat fd_stat;
776 int fd_stat_result = fstat(locked_fd->GetFd(), &fd_stat);
777 if (fd_stat_result != 0) {
778 PLOG(ERROR) << "Failed to fstat file descriptor of oat file " << oat_cache_filename;
779 return NULL;
780 }
781 struct stat file_stat;
782 int file_stat_result = stat(oat_cache_filename.c_str(), &file_stat);
783 if (file_stat_result != 0
784 || fd_stat.st_dev != file_stat.st_dev
785 || fd_stat.st_ino != file_stat.st_ino) {
786 LOG(INFO) << "Opened oat file " << oat_cache_filename << " is stale; sleeping and retrying";
787 usleep(250 * 1000); // if something is hosed, don't peg machine
788 continue;
789 }
790
791 // We have the correct file open and locked. If the file size is
792 // zero, then it was just created by us and we can generate its
793 // contents. If not, someone else created it. Either way, we'll
794 // loop to retry opening the file.
795 if (fd_stat.st_size == 0) {
796 bool success = GenerateOatFile(dex_file.GetLocation(),
797 locked_fd->GetFd(),
798 oat_cache_filename);
799 if (!success) {
800 LOG(ERROR) << "Failed to generate oat file " << oat_cache_filename;
801 return NULL;
802 }
803 }
jeffhao262bf462011-10-20 18:36:32 -0700804 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800805 // Not reached
Brian Carlstromaded5f72011-10-07 17:15:04 -0700806}
807
Brian Carlstromae826982011-11-09 01:33:42 -0800808const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700809 for (size_t i = 0; i < oat_files_.size(); i++) {
810 const OatFile* oat_file = oat_files_[i];
811 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800812 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700813 return oat_file;
814 }
815 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700816 return NULL;
817}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700818
Brian Carlstromae826982011-11-09 01:33:42 -0800819const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800820 const OatFile* oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700821 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800822 if (oat_location.empty() || oat_location[0] != '/') {
823 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700824 return NULL;
825 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700826
Brian Carlstroma9f19782011-10-13 00:14:47 -0700827 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Elliott Hughes95572412011-12-13 18:14:20 -0800828 std::string cache_location(GetArtCacheFilenameOrDie(oat_location));
Brian Carlstromae826982011-11-09 01:33:42 -0800829 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700830 if (oat_file != NULL) {
831 return oat_file;
832 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700833 oat_file = OatFile::Open(cache_location, "", NULL);
834 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800835 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700836 return NULL;
837 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700838 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700839
Brian Carlstromae826982011-11-09 01:33:42 -0800840 CHECK(oat_file != NULL) << oat_location;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700841 return oat_file;
842}
843
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700844void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800845 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700846 CHECK(!init_done_);
847
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700848 const std::vector<Space*>& spaces = Heap::GetSpaces();
849 for (size_t i = 0; i < spaces.size(); i++) {
Ian Rogers30fab402012-01-23 15:43:46 -0800850 if (spaces[i]->IsImageSpace()) {
851 ImageSpace* space = spaces[i]->AsImageSpace();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700852 OatFile* oat_file = OpenOat(space);
853 CHECK(oat_file != NULL) << "Failed to open oat file for image";
854 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
855 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
856
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800857 if (i == 0) {
858 // Special case of setting up the String class early so that we can test arbitrary objects
859 // as being Strings or not
Ian Rogers30fab402012-01-23 15:43:46 -0800860 Class* java_lang_String = space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800861 ->AsObjectArray<Class>()->Get(kJavaLangString);
862 String::SetClass(java_lang_String);
863 }
864
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700865 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
866 static_cast<uint32_t>(dex_caches->GetLength()));
867 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700868 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800869 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom89521892011-12-07 22:05:07 -0800870 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
871 const DexFile* dex_file = oat_dex_file->OpenDexFile();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700872 if (dex_file == NULL) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800873 LOG(FATAL) << "Failed to open dex file " << dex_file_location
874 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700875 }
876
Brian Carlstromaded5f72011-10-07 17:15:04 -0700877 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700878
Brian Carlstromdf143242011-10-10 18:05:34 -0700879 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700880 }
881 }
882 }
883
Brian Carlstroma663ea52011-08-19 23:33:41 -0700884 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
885 DCHECK(heap_bitmap != NULL);
886
Brian Carlstroma663ea52011-08-19 23:33:41 -0700887 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700888 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700889
890 // reinit class_roots_
Ian Rogers30fab402012-01-23 15:43:46 -0800891 Object* class_roots_object =
892 spaces[0]->AsImageSpace()->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700893 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700894
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800895 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700896 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
897 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800898 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700899 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700900 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700901 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
902 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
903 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
904 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
905 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
906 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
907 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
908 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700909 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700910 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700911
912 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700913
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800914 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700915}
916
Brian Carlstrom78128a62011-09-15 17:21:19 -0700917void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700918 DCHECK(obj != NULL);
919 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700920 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700921
Elliott Hughesdbb40792011-11-18 17:05:22 -0800922 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700923 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700924 return;
925 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700926 if (obj->IsClass()) {
927 // restore class to ClassLinker::classes_ table
928 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800929 ClassHelper kh(klass, class_linker);
Brian Carlstrom07bb8552012-01-18 22:10:50 -0800930 Class* existing = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
931 DCHECK(existing == NULL) << kh.GetDescriptor();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700932 return;
933 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700934}
935
936// Keep in sync with InitCallback. Anything we visit, we need to
937// reinit references to when reinitializing a ClassLinker from a
938// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700939void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
940 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700941
942 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700943 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700944 }
945
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700946 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700947 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700948 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700949 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700950 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700951 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700952 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700953 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700954
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700955 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700956}
957
Elliott Hughesa2155262011-11-16 16:26:58 -0800958void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
959 MutexLock mu(classes_lock_);
960 typedef Table::const_iterator It; // TODO: C++0x auto
961 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
962 if (!visitor(it->second, arg)) {
963 return;
964 }
965 }
966 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
967 if (!visitor(it->second, arg)) {
968 return;
969 }
970 }
971}
972
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700973ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700974 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700975 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700976 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700977 BooleanArray::ResetArrayClass();
978 ByteArray::ResetArrayClass();
979 CharArray::ResetArrayClass();
980 DoubleArray::ResetArrayClass();
981 FloatArray::ResetArrayClass();
982 IntArray::ResetArrayClass();
983 LongArray::ResetArrayClass();
984 ShortArray::ResetArrayClass();
985 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700986 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700987 STLDeleteElements(&boot_class_path_);
988 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700989}
990
991DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700992 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
993 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700994 return NULL;
995 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700996 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
997 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700998 return NULL;
999 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001000 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
1001 if (strings.get() == NULL) {
1002 return NULL;
1003 }
1004 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
1005 if (types.get() == NULL) {
1006 return NULL;
1007 }
1008 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
1009 if (methods.get() == NULL) {
1010 return NULL;
1011 }
1012 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
1013 if (fields.get() == NULL) {
1014 return NULL;
1015 }
1016 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
1017 if (code_and_direct_methods.get() == NULL) {
1018 return NULL;
1019 }
1020 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
1021 if (initialized_static_storage.get() == NULL) {
1022 return NULL;
1023 }
1024
1025 dex_cache->Init(location.get(),
1026 strings.get(),
1027 types.get(),
1028 methods.get(),
1029 fields.get(),
1030 code_and_direct_methods.get(),
1031 initialized_static_storage.get());
1032 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001033}
1034
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001035CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
1036 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -07001037}
1038
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001039InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
1040 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001041 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
1042 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001043 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001044 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001045}
1046
Brian Carlstrom4873d462011-08-21 15:23:39 -07001047Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
1048 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001049 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001050 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001051 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001052 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001053}
1054
Brian Carlstrom4873d462011-08-21 15:23:39 -07001055Class* ClassLinker::AllocClass(size_t class_size) {
1056 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001057}
1058
Jesse Wilson35baaab2011-08-10 16:18:03 -04001059Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001060 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -07001061}
1062
1063Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001064 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001065}
1066
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001067ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
1068 return ObjectArray<StackTraceElement>::Alloc(
1069 GetClassRoot(kJavaLangStackTraceElementArrayClass),
1070 length);
1071}
1072
Brian Carlstromaded5f72011-10-07 17:15:04 -07001073Class* EnsureResolved(Class* klass) {
1074 DCHECK(klass != NULL);
1075 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -07001076 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001077 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001078 ObjectLock lock(klass);
1079 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001080 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001081 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001082 PrettyDescriptor(klass).c_str());
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001083 klass->SetStatus(Class::kStatusError);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001084 return NULL;
1085 }
1086 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001087 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001088 lock.Wait();
1089 }
1090 }
1091 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001092 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001093 return NULL;
1094 }
1095 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001096 CHECK(klass->IsResolved()) << PrettyClass(klass);
1097 CHECK(!self->IsExceptionPending())
1098 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
1099 return klass;
1100}
1101
Elliott Hughesdb7d5e92011-12-16 18:47:37 -08001102Class* ClassLinker::FindSystemClass(const char* descriptor) {
1103 return FindClass(descriptor, NULL);
1104}
1105
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001106Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001107 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001108 Thread* self = Thread::Current();
1109 DCHECK(self != NULL);
1110 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001111 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001112 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1113 // for primitive classes that aren't backed by dex files.
1114 return FindPrimitiveClass(descriptor[0]);
1115 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001116 // Find the class in the loaded classes table.
1117 Class* klass = LookupClass(descriptor, class_loader);
1118 if (klass != NULL) {
1119 return EnsureResolved(klass);
1120 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001121 // Class is not yet loaded.
1122 if (descriptor[0] == '[') {
1123 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001124
Jesse Wilson47daf872011-11-23 11:42:45 -05001125 } else if (class_loader == NULL) {
1126 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1127 if (pair.second != NULL) {
1128 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1129 }
1130
1131 } else if (ClassLoader::UseCompileTimeClassPath()) {
1132 // first try the boot class path
1133 Class* system_class = FindSystemClass(descriptor);
1134 if (system_class != NULL) {
1135 return system_class;
1136 }
1137 CHECK(self->IsExceptionPending());
1138 self->ClearException();
1139
1140 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001141 const std::vector<const DexFile*>& class_path
1142 = ClassLoader::GetCompileTimeClassPath(class_loader);
1143 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001144 if (pair.second != NULL) {
1145 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001146 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001147
1148 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001149 std::string class_name_string(DescriptorToDot(descriptor));
Jesse Wilson47daf872011-11-23 11:42:45 -05001150 ScopedThreadStateChange(self, Thread::kNative);
Elliott Hughes748382f2012-01-26 18:07:38 -08001151 JNIEnv* env = self->GetJniEnv();
Jesse Wilson47daf872011-11-23 11:42:45 -05001152 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1153 CHECK(c.get() != NULL);
1154 // TODO: cache method?
1155 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1156 CHECK(mid != NULL);
1157 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1158 if (class_name_object.get() == NULL) {
1159 return NULL;
1160 }
1161 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
Ian Rogers761bfa82012-01-11 10:14:05 -08001162 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid,
1163 class_name_object.get()));
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001164 if (env->ExceptionCheck()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001165 // If the ClassLoader threw, pass that exception up.
1166 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001167 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001168 // broken loader - throw NPE to be compatible with Dalvik
1169 ThrowNullPointerException("ClassLoader.loadClass returned null for %s",
1170 class_name_string.c_str());
1171 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001172 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08001173 // success, return Class*
Ian Rogers6b0870d2011-12-15 19:38:12 -08001174 return Decode<Class*>(env, result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001175 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001176 }
1177
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001178 ThrowNoClassDefFoundError("Class %s not found", PrintableString(StringPiece(descriptor)).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001179 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001180}
1181
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001182Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001183 const ClassLoader* class_loader,
1184 const DexFile& dex_file,
1185 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001186 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001187 // Load the class from the dex file.
1188 if (!init_done_) {
1189 // finish up init of hand crafted class_roots_
1190 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001191 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001192 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001193 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001194 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001195 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001196 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001197 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001198 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001199 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001200 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001201 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001202 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001203 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001204 }
1205 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001206 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001207 }
1208 klass->SetDexCache(FindDexCache(dex_file));
1209 LoadClass(dex_file, dex_class_def, klass, class_loader);
1210 // Check for a pending exception during load
1211 Thread* self = Thread::Current();
1212 if (self->IsExceptionPending()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001213 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001214 return NULL;
1215 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001216 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001217 klass->SetClinitThreadId(self->GetTid());
1218 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001219 Class* existing = InsertClass(descriptor, klass.get(), false);
1220 if (existing != NULL) {
1221 // We failed to insert because we raced with another thread.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001222 klass->SetClinitThreadId(0);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001223 klass.reset(existing);
1224 return EnsureResolved(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001225 }
1226 // Finish loading (if necessary) by finding parents
1227 CHECK(!klass->IsLoaded());
1228 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1229 // Loading failed.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001230 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001231 lock.NotifyAll();
1232 return NULL;
1233 }
1234 CHECK(klass->IsLoaded());
1235 // Link the class (if necessary)
1236 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001237 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001238 // Linking failed.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001239 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001240 lock.NotifyAll();
1241 return NULL;
1242 }
1243 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001244
1245 /*
1246 * We send CLASS_PREPARE events to the debugger from here. The
1247 * definition of "preparation" is creating the static fields for a
1248 * class and initializing them to the standard default values, but not
1249 * executing any code (that comes later, during "initialization").
1250 *
1251 * We did the static preparation in LinkClass.
1252 *
1253 * The class has been prepared and resolved but possibly not yet verified
1254 * at this point.
1255 */
1256 Dbg::PostClassPrepare(klass.get());
1257
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001258 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001259}
1260
Brian Carlstrom4873d462011-08-21 15:23:39 -07001261// Precomputes size that will be needed for Class, matching LinkStaticFields
1262size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1263 const DexFile::ClassDef& dex_class_def) {
1264 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001265 size_t num_ref = 0;
1266 size_t num_32 = 0;
1267 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001268 if (class_data != NULL) {
1269 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1270 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001271 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001272 char c = descriptor[0];
1273 if (c == 'L' || c == '[') {
1274 num_ref++;
1275 } else if (c == 'J' || c == 'D') {
1276 num_64++;
1277 } else {
1278 num_32++;
1279 }
1280 }
1281 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001282 // start with generic class data
1283 size_t size = sizeof(Class);
1284 // follow with reference fields which must be contiguous at start
1285 size += (num_ref * sizeof(uint32_t));
1286 // if there are 64-bit fields to add, make sure they are aligned
1287 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1288 if (num_32 != 0) {
1289 // use an available 32-bit field for padding
1290 num_32--;
1291 }
1292 size += sizeof(uint32_t); // either way, we are adding a word
1293 DCHECK_EQ(size, RoundUp(size, 8));
1294 }
1295 // tack on any 64-bit fields now that alignment is assured
1296 size += (num_64 * sizeof(uint64_t));
1297 // tack on any remaining 32-bit fields
1298 size += (num_32 * sizeof(uint32_t));
1299 return size;
1300}
1301
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001302void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001303 // Every kind of method should at least get an invoke stub from the oat_method.
1304 // non-abstract methods also get their code pointers.
1305 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001306 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001307
1308 if (method->IsAbstract()) {
1309 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1310 return;
1311 }
1312 if (method->IsNative()) {
1313 // unregistering restores the dlsym lookup stub
1314 method->UnregisterNative();
jeffhao26c0a1a2012-01-17 16:28:33 -08001315 }
1316
1317 if (Runtime::Current()->IsMethodTracingActive()) {
1318#if defined(__arm__)
1319 Trace* tracer = Runtime::Current()->GetTracer();
1320 void* trace_stub = reinterpret_cast<void*>(art_trace_entry_from_code);
1321 tracer->SaveAndUpdateCode(method.get(), trace_stub);
1322#else
1323 UNIMPLEMENTED(WARNING);
1324#endif
Brian Carlstrom92827a52011-10-10 15:50:01 -07001325 }
1326}
1327
Brian Carlstromf615a612011-07-23 12:50:34 -07001328void ClassLinker::LoadClass(const DexFile& dex_file,
1329 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001330 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001331 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001332 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001333 CHECK(klass->GetDexCache() != NULL);
1334 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001335 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001336 CHECK(descriptor != NULL);
1337
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001338 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001339 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001340 // Make sure that none of our runtime-only flags are set.
1341 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001342 klass->SetAccessFlags(access_flags);
1343 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001344 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001345 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001346
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001347 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001348
Ian Rogers0571d352011-11-03 19:51:38 -07001349 // Load fields fields.
1350 const byte* class_data = dex_file.GetClassData(dex_class_def);
1351 if (class_data == NULL) {
1352 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001353 }
Ian Rogers0571d352011-11-03 19:51:38 -07001354 ClassDataItemIterator it(dex_file, class_data);
1355 if (it.NumStaticFields() != 0) {
1356 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1357 }
1358 if (it.NumInstanceFields() != 0) {
1359 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1360 }
1361 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1362 SirtRef<Field> sfield(AllocField());
1363 klass->SetStaticField(i, sfield.get());
1364 LoadField(dex_file, it, klass, sfield);
1365 }
1366 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1367 SirtRef<Field> ifield(AllocField());
1368 klass->SetInstanceField(i, ifield.get());
1369 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001370 }
1371
Brian Carlstromaded5f72011-10-07 17:15:04 -07001372 UniquePtr<const OatFile::OatClass> oat_class;
1373 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001374 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001375 if (oat_file != NULL) {
1376 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1377 if (oat_dex_file != NULL) {
1378 uint32_t class_def_index;
1379 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1380 CHECK(found) << descriptor;
1381 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001382 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001383 }
1384 }
1385 }
Ian Rogers0571d352011-11-03 19:51:38 -07001386 // Load methods.
1387 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001388 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001389 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001390 }
Ian Rogers0571d352011-11-03 19:51:38 -07001391 if (it.NumVirtualMethods() != 0) {
1392 // TODO: append direct methods to class object
1393 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001394 }
Ian Rogers0571d352011-11-03 19:51:38 -07001395 size_t method_index = 0;
1396 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1397 SirtRef<Method> method(AllocMethod());
1398 klass->SetDirectMethod(i, method.get());
1399 LoadMethod(dex_file, it, klass, method);
1400 if (oat_class.get() != NULL) {
1401 LinkCode(method, oat_class.get(), method_index);
1402 }
1403 method_index++;
1404 }
1405 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1406 SirtRef<Method> method(AllocMethod());
1407 klass->SetVirtualMethod(i, method.get());
1408 LoadMethod(dex_file, it, klass, method);
1409 if (oat_class.get() != NULL) {
1410 LinkCode(method, oat_class.get(), method_index);
1411 }
1412 method_index++;
1413 }
1414 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001415}
1416
Ian Rogers0571d352011-11-03 19:51:38 -07001417void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1418 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001419 uint32_t field_idx = it.GetMemberIndex();
1420 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001421 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001422 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001423}
1424
Ian Rogers0571d352011-11-03 19:51:38 -07001425void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1426 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001427 uint32_t method_idx = it.GetMemberIndex();
1428 dst->SetDexMethodIndex(method_idx);
1429 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001430 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001431
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001432
1433 StringPiece method_name(dex_file.GetMethodName(method_id));
1434 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001435 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1436 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001437
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001438 if (method_name == "finalize") {
1439 // Create the prototype for a signature of "()V"
1440 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1441 if (void_string_id != NULL) {
1442 const DexFile::TypeId* void_type_id =
1443 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1444 if (void_type_id != NULL) {
1445 std::vector<uint16_t> no_args;
1446 const DexFile::ProtoId* finalizer_proto =
1447 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1448 if (finalizer_proto != NULL) {
1449 // We have the prototype in the dex file
1450 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1451 klass->SetFinalizable();
1452 } else {
1453 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1454 // The Enum class declares a "final" finalize() method to prevent subclasses from
1455 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1456 // subclasses, so we exclude it here.
1457 // We also want to avoid setting the flag on Object, where we know that finalize() is
1458 // empty.
1459 if (klass_descriptor != "Ljava/lang/Object;" &&
1460 klass_descriptor != "Ljava/lang/Enum;") {
1461 klass->SetFinalizable();
1462 }
1463 }
1464 }
1465 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001466 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001467 }
Ian Rogers0571d352011-11-03 19:51:38 -07001468 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001469 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001470
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001471 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1472 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1473 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1474 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1475 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1476 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001477}
1478
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001479void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001480 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1481 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001482}
1483
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001484void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1485 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001486 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001487 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001488}
1489
Brian Carlstromaded5f72011-10-07 17:15:04 -07001490bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001491 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001492 for (size_t i = 0; i != dex_files_.size(); ++i) {
1493 if (dex_files_[i] == &dex_file) {
1494 return true;
1495 }
1496 }
1497 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001498}
1499
Brian Carlstromaded5f72011-10-07 17:15:04 -07001500bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001501 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001502 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001503}
1504
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001505void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001506 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001507 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001508 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001509 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001510 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001511}
1512
Brian Carlstromaded5f72011-10-07 17:15:04 -07001513void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001514 {
1515 MutexLock mu(dex_lock_);
1516 if (IsDexFileRegisteredLocked(dex_file)) {
1517 return;
1518 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001519 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001520 // Don't alloc while holding the lock, since allocation may need to
1521 // suspend all threads and another thread may need the dex_lock_ to
1522 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001523 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001524 {
1525 MutexLock mu(dex_lock_);
1526 if (IsDexFileRegisteredLocked(dex_file)) {
1527 return;
1528 }
1529 RegisterDexFileLocked(dex_file, dex_cache);
1530 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001531}
1532
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001533void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001534 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001535 RegisterDexFileLocked(dex_file, dex_cache);
1536}
1537
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001538const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001539 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001540 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001541 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1542 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001543 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001544 }
1545 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001546 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001547 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001548}
1549
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001550DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001551 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001552 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001553 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001554 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001555 }
1556 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001557 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001558 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001559}
1560
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001561Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1562 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001563 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001564 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001565 CHECK(primitive_class != NULL);
1566 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001567 primitive_class->SetPrimitiveType(type);
1568 primitive_class->SetStatus(Class::kStatusInitialized);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001569 Class* existing = InsertClass(descriptor, primitive_class, false);
1570 CHECK(existing == NULL) << "InitPrimitiveClass(" << descriptor << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001571 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001572}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001573
Brian Carlstrombe977852011-07-19 14:54:54 -07001574// Create an array class (i.e. the class object for the array, not the
1575// array itself). "descriptor" looks like "[C" or "[[[[B" or
1576// "[Ljava/lang/String;".
1577//
1578// If "descriptor" refers to an array of primitives, look up the
1579// primitive type's internally-generated class object.
1580//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001581// "class_loader" is the class loader of the class that's referring to
1582// us. It's used to ensure that we're looking for the element type in
1583// the right context. It does NOT become the class loader for the
1584// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001585//
1586// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001587Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001588 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001589
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001590 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001591 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001592 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001593 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001594 return NULL;
1595 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001596
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001597 // See if the component type is already loaded. Array classes are
1598 // always associated with the class loader of their underlying
1599 // element type -- an array of Strings goes with the loader for
1600 // java/lang/String -- so we need to look for it there. (The
1601 // caller should have checked for the existence of the class
1602 // before calling here, but they did so with *their* class loader,
1603 // not the component type's loader.)
1604 //
1605 // If we find it, the caller adds "loader" to the class' initiating
1606 // loader list, which should prevent us from going through this again.
1607 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001608 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001609 // are the same, because our caller (FindClass) just did the
1610 // lookup. (Even if we get this wrong we still have correct behavior,
1611 // because we effectively do this lookup again when we add the new
1612 // class to the hash table --- necessary because of possible races with
1613 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001614 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001615 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001616 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001617 return new_class;
1618 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001619 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001620
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001621 // Fill out the fields in the Class.
1622 //
1623 // It is possible to execute some methods against arrays, because
1624 // all arrays are subclasses of java_lang_Object_, so we need to set
1625 // up a vtable. We can just point at the one in java_lang_Object_.
1626 //
1627 // Array classes are simple enough that we don't need to do a full
1628 // link step.
1629
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001630 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001631 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001632 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001633 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001634 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001635 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001636 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001637 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001638 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001639 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001640 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001641 }
1642 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001643 if (new_class.get() == NULL) {
1644 new_class.reset(AllocClass(sizeof(Class)));
1645 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001646 return NULL;
1647 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001648 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001649 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001650 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001651 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001652 new_class->SetSuperClass(java_lang_Object);
1653 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001654 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001655 new_class->SetClassLoader(component_type->GetClassLoader());
1656 new_class->SetStatus(Class::kStatusInitialized);
1657 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001658 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001659
1660
1661 // All arrays have java/lang/Cloneable and java/io/Serializable as
1662 // interfaces. We need to set that up here, so that stuff like
1663 // "instanceof" works right.
1664 //
1665 // Note: The GC could run during the call to FindSystemClass,
1666 // so we need to make sure the class object is GC-valid while we're in
1667 // there. Do this by clearing the interface list so the GC will just
1668 // think that the entries are null.
1669
1670
1671 // Use the single, global copies of "interfaces" and "iftable"
1672 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001673 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001674 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001675
1676 // Inherit access flags from the component type. Arrays can't be
1677 // used as a superclass or interface, so we want to add "final"
1678 // and remove "interface".
1679 //
1680 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001681 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001682 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001683 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1684 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001685
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001686 Class* existing = InsertClass(descriptor, new_class.get(), false);
1687 if (existing == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001688 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001689 }
1690 // Another thread must have loaded the class after we
1691 // started but before we finished. Abandon what we've
1692 // done.
1693 //
1694 // (Yes, this happens.)
1695
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001696 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001697}
1698
1699Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001700 switch (Primitive::GetType(type)) {
1701 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001702 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001703 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001704 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001705 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001706 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001707 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001708 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001709 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001710 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001711 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001712 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001713 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001714 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001715 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001716 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001717 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001718 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001719 case Primitive::kPrimNot:
1720 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001721 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001722 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001723 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001724 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001725}
1726
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001727Class* ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001728 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001729 DexCache* dex_cache = klass->GetDexCache();
1730 std::string source;
1731 if (dex_cache != NULL) {
1732 source += " from ";
1733 source += dex_cache->GetLocation()->ToModifiedUtf8();
1734 }
1735 LOG(INFO) << "Loaded class " << descriptor << source;
1736 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001737 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001738 MutexLock mu(classes_lock_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001739 Table& classes = image_class ? image_classes_ : classes_;
1740 Class* existing = LookupClass(descriptor.data(), klass->GetClassLoader(), hash, classes);
1741#ifndef NDEBUG
1742 // Check we don't have the class in the other table in error
1743 Table& other_classes = image_class ? classes_ : image_classes_;
1744 CHECK(LookupClass(descriptor.data(), klass->GetClassLoader(), hash, other_classes) == NULL);
1745#endif
1746 if (existing != NULL) {
1747 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07001748 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001749 classes.insert(std::make_pair(hash, klass));
1750 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001751}
1752
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001753bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1754 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001755 MutexLock mu(classes_lock_);
Elliott Hughese5448b52012-01-18 16:44:06 -08001756 typedef Table::iterator It; // TODO: C++0x auto
Brian Carlstromae826982011-11-09 01:33:42 -08001757 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001758 ClassHelper kh;
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001759 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001760 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001761 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001762 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001763 classes_.erase(it);
1764 return true;
1765 }
1766 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001767 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001768 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001769 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001770 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001771 image_classes_.erase(it);
1772 return true;
1773 }
1774 }
1775 return false;
1776}
1777
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001778Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1779 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001780 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001781 // TODO: determine if its better to search classes_ or image_classes_ first
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001782 Class* klass = LookupClass(descriptor, class_loader, hash, classes_);
1783 if (klass != NULL) {
1784 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001785 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001786 return LookupClass(descriptor, class_loader, hash, image_classes_);
1787}
1788
1789Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader,
1790 size_t hash, const Table& classes) {
1791 ClassHelper kh(NULL, this);
1792 typedef Table::const_iterator It; // TODO: C++0x auto
1793 for (It it = classes.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001794 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001795 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001796 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001797#ifndef NDEBUG
1798 for (++it; it != end && it->first == hash; ++it) {
1799 kh.ChangeClass(it->second);
1800 CHECK(!(strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader))
1801 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
1802 << PrettyClass(it->second) << " " << it->second << " " << it->second->GetClassLoader();
1803 }
1804#endif
Ian Rogers5d76c432011-10-31 21:42:49 -07001805 return klass;
1806 }
1807 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001808 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001809}
1810
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001811void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001812 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001813 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001814 MutexLock mu(classes_lock_);
1815 typedef Table::const_iterator It; // TODO: C++0x auto
1816 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001817 ClassHelper kh(NULL, this);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001818 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001819 Class* klass = it->second;
1820 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001821 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001822 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001823 }
1824 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001825 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001826 Class* klass = it->second;
1827 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001828 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001829 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001830 }
1831 }
1832}
1833
Ian Rogersc20a83e2012-01-18 18:15:32 -08001834#ifndef NDEBUG
1835static void CheckMethodsHaveGcMaps(Class* klass) {
1836 if (!Runtime::Current()->IsStarted()) {
1837 return;
1838 }
1839 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
1840 Method* method = klass->GetDirectMethod(i);
1841 if (!method->IsNative() && !method->IsAbstract()) {
1842 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1843 }
1844 }
1845 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
1846 Method* method = klass->GetVirtualMethod(i);
1847 if (!method->IsNative() && !method->IsAbstract()) {
1848 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1849 }
1850 }
1851}
1852#else
1853static void CheckMethodsHaveGcMaps(Class* klass) {
1854}
1855#endif
1856
jeffhao98eacac2011-09-14 16:11:53 -07001857void ClassLinker::VerifyClass(Class* klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001858 // TODO: assert that the monitor on the Class is held
jeffhao98eacac2011-09-14 16:11:53 -07001859 if (klass->IsVerified()) {
1860 return;
1861 }
1862
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001863 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved) << PrettyClass(klass);
jeffhao98eacac2011-09-14 16:11:53 -07001864 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001865
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001866 // Try to use verification information from oat file, otherwise do runtime verification
1867 const DexFile& dex_file = FindDexFile(klass->GetDexCache());
1868 if (VerifyClassUsingOatFile(dex_file, klass) || verifier::DexVerifier::VerifyClass(klass)) {
1869 // Make sure all classes referenced by catch blocks are resolved
1870 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001871 klass->SetStatus(Class::kStatusVerified);
Ian Rogersc20a83e2012-01-18 18:15:32 -08001872 // Sanity check that a verified class has GC maps on all methods
1873 CheckMethodsHaveGcMaps(klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001874 } else {
1875 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001876 Thread* self = Thread::Current();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001877 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException()) << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001878 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001879 PrettyDescriptor(klass).c_str());
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001880 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001881 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001882 }
jeffhao98eacac2011-09-14 16:11:53 -07001883}
1884
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001885bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, Class* klass) {
1886 if (!Runtime::Current()->IsStarted()) {
1887 return false;
1888 }
1889 if (ClassLoader::UseCompileTimeClassPath()) {
1890 return false;
1891 }
1892 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
1893 if (oat_file == NULL) {
1894 return false;
1895 }
1896 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1897 CHECK(oat_dex_file != NULL) << PrettyClass(klass);
1898 const char* descriptor = ClassHelper(klass).GetDescriptor();
1899 uint32_t class_def_index;
1900 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1901 CHECK(found) << descriptor;
1902 UniquePtr<const OatFile::OatClass> oat_class(oat_dex_file->GetOatClass(class_def_index));
1903 CHECK(oat_class.get() != NULL) << descriptor;
1904 Class::Status status = oat_class->GetStatus();
1905 if (status == Class::kStatusError) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001906 // TODO: include appropriate verify_error_class_ information in oat file for use here.
1907 ThrowNoClassDefFoundError("Class failed compile-time verification: %s",
1908 PrettyDescriptor(klass).c_str());
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001909 klass->SetStatus(Class::kStatusError);
1910 return true;
1911 }
1912 if (status == Class::kStatusVerified || status == Class::kStatusInitialized) {
1913 return true;
1914 }
1915 if (status == Class::kStatusNotReady) {
1916 return false;
1917 }
1918 LOG(FATAL) << "Unexpected class status: " << status;
1919 return false;
1920}
1921
1922void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, Class* klass) {
1923 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
1924 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
1925 }
1926 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
1927 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
1928 }
1929}
1930
1931void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, Method* method) {
1932 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
1933 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
1934 if (code_item == NULL) {
1935 return; // native or abstract method
1936 }
1937 if (code_item->tries_size_ == 0) {
1938 return; // nothing to process
1939 }
1940 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
1941 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
1942 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1943 for (uint32_t idx = 0; idx < handlers_size; idx++) {
1944 CatchHandlerIterator iterator(handlers_ptr);
1945 for (; iterator.HasNext(); iterator.Next()) {
1946 // Ensure exception types are resolved so that they don't need resolution to be delivered,
1947 // unresolved exception types will be ignored by exception delivery
1948 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
1949 Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
1950 if (exception_type == NULL) {
1951 DCHECK(Thread::Current()->IsExceptionPending());
1952 Thread::Current()->ClearException();
1953 }
1954 }
1955 }
1956 handlers_ptr = iterator.EndDataPointer();
1957 }
1958}
1959
Ian Rogersc2b44472011-12-14 21:17:17 -08001960static void CheckProxyConstructor(Method* constructor);
1961static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
1962
Jesse Wilson95caa792011-10-12 18:14:17 -04001963Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001964 ClassLoader* loader, ObjectArray<Method>* methods,
1965 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08001966 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001967 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08001968 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001969 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001970 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001971 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001972 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001973 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07001974 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001975 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08001976
1977 klass->SetStatus(Class::kStatusIdx);
1978
1979 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
1980
1981 // Create static field that holds throws, instance fields are inherited
1982 klass->SetSFields(AllocObjectArray<Field>(1));
1983 SirtRef<Field> sfield(AllocField());
1984 klass->SetStaticField(0, sfield.get());
1985 sfield->SetDexFieldIndex(-1);
1986 sfield->SetDeclaringClass(klass.get());
1987 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001988
Ian Rogers466bb252011-10-14 03:29:56 -07001989 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001990 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001991 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04001992
Ian Rogers466bb252011-10-14 03:29:56 -07001993 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001994 size_t num_virtual_methods = methods->GetLength();
1995 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1996 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001997 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001998 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04001999 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002000
2001 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
2002 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
2003 DCHECK(!Thread::Current()->IsExceptionPending());
2004
2005 // Link the fields and virtual methods, creating vtable and iftables
2006 if (!LinkClass(klass, interfaces)) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002007 klass->SetStatus(Class::kStatusError);
Jesse Wilson95caa792011-10-12 18:14:17 -04002008 return NULL;
2009 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002010 sfield->SetObject(NULL, throws); // initialize throws field
2011 klass->SetStatus(Class::kStatusInitialized);
2012
2013 // sanity checks
2014#ifndef NDEBUG
2015 bool debug = true;
2016#else
2017 bool debug = false;
2018#endif
2019 if (debug) {
2020 CHECK(klass->GetIFields() == NULL);
2021 CheckProxyConstructor(klass->GetDirectMethod(0));
2022 for (size_t i = 0; i < num_virtual_methods; ++i) {
2023 SirtRef<Method> prototype(methods->Get(i));
2024 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
2025 }
Brian Carlstrom89521892011-12-07 22:05:07 -08002026 std::string throws_field_name("java.lang.Class[][] ");
Ian Rogersc2b44472011-12-14 21:17:17 -08002027 throws_field_name += name->ToModifiedUtf8();
2028 throws_field_name += ".throws";
2029 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
2030
2031 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
2032 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
2033 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002034 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04002035}
2036
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002037std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
2038 DCHECK(proxy_class->IsProxyClass());
2039 String* name = proxy_class->GetName();
2040 DCHECK(name != NULL);
2041 return DotToDescriptor(name->ToModifiedUtf8().c_str());
2042}
2043
2044
2045Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07002046 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07002047 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04002048 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07002049 Method* proxy_constructor = proxy_direct_methods->Get(2);
2050 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
2051 // code_ too)
2052 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
2053 // Make this constructor public and fix the class to be our Proxy version
2054 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002055 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08002056 return constructor;
2057}
2058
2059static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07002060 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002061 MethodHelper mh(constructor);
2062 CHECK_STREQ(mh.GetName(), "<init>");
Elliott Hughesba8eee12012-01-24 20:25:24 -08002063 CHECK_EQ(mh.GetSignature(), std::string("(Ljava/lang/reflect/InvocationHandler;)V"));
Ian Rogers466bb252011-10-14 03:29:56 -07002064 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04002065}
2066
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002067Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
2068 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
2069 // prototype method
2070 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
2071 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07002072 // as necessary
2073 Method* method = down_cast<Method*>(prototype->Clone());
2074
2075 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
2076 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002077 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07002078 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002079
Ian Rogers466bb252011-10-14 03:29:56 -07002080 // At runtime the method looks like a reference and argument saving method, clone the code
2081 // related parameters from this method.
2082 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
2083 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
2084 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
2085 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
2086 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08002087 return method;
2088}
Jesse Wilson95caa792011-10-12 18:14:17 -04002089
Ian Rogersc2b44472011-12-14 21:17:17 -08002090static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07002091 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002092 CHECK(!prototype->IsFinal());
2093 CHECK(method->IsFinal());
2094 CHECK(!method->IsAbstract());
2095 MethodHelper mh(method);
2096 const char* method_name = mh.GetName();
2097 const char* method_shorty = mh.GetShorty();
2098 Class* method_return = mh.GetReturnType();
2099
2100 mh.ChangeMethod(prototype.get());
2101
2102 CHECK_STREQ(mh.GetName(), method_name);
2103 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07002104
2105 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002106 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04002107}
2108
Brian Carlstrom25c33252011-09-18 15:58:35 -07002109bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002110 CHECK(klass->IsResolved() || klass->IsErroneous())
2111 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002112
Carl Shapirob5573532011-07-12 18:22:59 -07002113 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002114
Brian Carlstrom25c33252011-09-18 15:58:35 -07002115 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002116 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002117 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002118 ObjectLock lock(klass);
2119
Brian Carlstromd1422f82011-09-28 11:37:09 -07002120 if (klass->GetStatus() == Class::kStatusInitialized) {
2121 return true;
2122 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002123
Brian Carlstromd1422f82011-09-28 11:37:09 -07002124 if (klass->IsErroneous()) {
2125 ThrowEarlierClassFailure(klass);
2126 return false;
2127 }
2128
2129 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07002130 VerifyClass(klass);
2131 if (klass->GetStatus() != Class::kStatusVerified) {
Ian Rogers595799e2012-01-11 17:32:51 -08002132 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002133 return false;
2134 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002135 }
2136
Brian Carlstrom25c33252011-09-18 15:58:35 -07002137 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
2138 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002139 // if the class has a <clinit> but we can't run it during compilation,
Ian Rogers595799e2012-01-11 17:32:51 -08002140 // don't bother going to kStatusInitializing. We return true to maintain
2141 // the invariant that a false result implies there is a pending exception.
2142 return true;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002143 }
2144
Brian Carlstromd1422f82011-09-28 11:37:09 -07002145 // If the class is kStatusInitializing, either this thread is
2146 // initializing higher up the stack or another thread has beat us
2147 // to initializing and we need to wait. Either way, this
2148 // invocation of InitializeClass will not be responsible for
2149 // running <clinit> and will return.
2150 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002151 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002152 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002153 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002154 return true;
2155 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002156 // No. That's fine. Wait for another thread to finish initializing.
2157 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002158 }
2159
2160 if (!ValidateSuperClassDescriptors(klass)) {
2161 klass->SetStatus(Class::kStatusError);
2162 return false;
2163 }
2164
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002165 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified) << PrettyClass(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002166
Elliott Hughesdcc24742011-09-07 14:02:44 -07002167 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002168 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002169 }
2170
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002171 uint64_t t0 = NanoTime();
2172
Brian Carlstrom25c33252011-09-18 15:58:35 -07002173 if (!InitializeSuperClass(klass, can_run_clinit)) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002174 CHECK(klass->IsErroneous());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002175 return false;
2176 }
2177
2178 InitializeStaticFields(klass);
2179
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002180 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002181 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002182 }
2183
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002184 uint64_t t1 = NanoTime();
2185
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002186 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002187 {
2188 ObjectLock lock(klass);
2189
2190 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002191 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002192 klass->SetStatus(Class::kStatusError);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002193 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002194 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002195 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2196 RuntimeStats* thread_stats = self->GetStats();
2197 ++global_stats->class_init_count;
2198 ++thread_stats->class_init_count;
2199 global_stats->class_init_time_ns += (t1 - t0);
2200 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002201 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002202 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002203 ClassHelper kh(klass);
2204 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002205 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002206 }
2207 lock.NotifyAll();
2208 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002209 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002210}
2211
Brian Carlstromd1422f82011-09-28 11:37:09 -07002212bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
2213 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002214 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002215 lock.Wait();
2216
2217 // When we wake up, repeat the test for init-in-progress. If
2218 // there's an exception pending (only possible if
2219 // "interruptShouldThrow" was set), bail out.
2220 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002221 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002222 klass->SetStatus(Class::kStatusError);
2223 return false;
2224 }
2225 // Spurious wakeup? Go back to waiting.
2226 if (klass->GetStatus() == Class::kStatusInitializing) {
2227 continue;
2228 }
2229 if (klass->IsErroneous()) {
2230 // The caller wants an exception, but it was thrown in a
2231 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002232 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002233 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002234 return false;
2235 }
2236 if (klass->IsInitialized()) {
2237 return true;
2238 }
2239 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2240 }
2241 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2242}
2243
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002244bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2245 if (klass->IsInterface()) {
2246 return true;
2247 }
2248 // begin with the methods local to the superclass
2249 if (klass->HasSuperClass() &&
2250 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2251 const Class* super = klass->GetSuperClass();
Ian Rogers595799e2012-01-11 17:32:51 -08002252 for (int i = super->GetVTable()->GetLength() - 1; i >= 0; --i) {
2253 const Method* method = klass->GetVTable()->Get(i);
2254 if (method != super->GetVTable()->Get(i) &&
2255 !IsSameMethodSignatureInDifferentClassContexts(method, super, klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002256 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2257 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2258 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002259 return false;
2260 }
2261 }
2262 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002263 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2264 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2265 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002266 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2267 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002268 const Method* method = interface_entry->GetMethodArray()->Get(j);
Ian Rogers595799e2012-01-11 17:32:51 -08002269 if (!IsSameMethodSignatureInDifferentClassContexts(method, interface,
2270 method->GetDeclaringClass())) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002271 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2272 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2273 PrettyMethod(method).c_str(),
2274 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002275 return false;
2276 }
2277 }
2278 }
2279 }
2280 return true;
2281}
2282
Ian Rogers595799e2012-01-11 17:32:51 -08002283// Returns true if classes referenced by the signature of the method are the
2284// same classes in klass1 as they are in klass2.
2285bool ClassLinker::IsSameMethodSignatureInDifferentClassContexts(const Method* method,
2286 const Class* klass1,
2287 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002288 if (klass1 == klass2) {
2289 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002290 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002291 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002292 const DexFile::ProtoId& proto_id =
2293 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002294 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2295 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002296 if (descriptor == NULL) {
2297 break;
2298 }
2299 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2300 // Found a non-primitive type.
Ian Rogers595799e2012-01-11 17:32:51 -08002301 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002302 return false;
2303 }
2304 }
2305 }
2306 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002307 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002308 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Ian Rogers595799e2012-01-11 17:32:51 -08002309 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002310 return false;
2311 }
2312 }
2313 return true;
2314}
2315
Ian Rogers595799e2012-01-11 17:32:51 -08002316// Returns true if the descriptor resolves to the same class in the context of klass1 and klass2.
2317bool ClassLinker::IsSameDescriptorInDifferentClassContexts(const char* descriptor,
2318 const Class* klass1,
2319 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002320 CHECK(descriptor != NULL);
2321 CHECK(klass1 != NULL);
2322 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002323 if (klass1 == klass2) {
2324 return true;
2325 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002326 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Ian Rogers595799e2012-01-11 17:32:51 -08002327 if (found1 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002328 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002329 }
Ian Rogers595799e2012-01-11 17:32:51 -08002330 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
2331 if (found2 == NULL) {
2332 Thread::Current()->ClearException();
2333 }
2334 return found1 == found2;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002335}
2336
Brian Carlstrom25c33252011-09-18 15:58:35 -07002337bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002338 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002339 if (!klass->IsInterface() && klass->HasSuperClass()) {
2340 Class* super_class = klass->GetSuperClass();
2341 if (super_class->GetStatus() != Class::kStatusInitialized) {
2342 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002343 Thread* self = Thread::Current();
2344 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002345 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002346 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002347 // TODO: check for a pending exception
2348 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002349 if (!can_run_clinit) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002350 // Don't set status to error when we can't run <clinit>.
2351 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing) << PrettyClass(klass);
2352 klass->SetStatus(Class::kStatusVerified);
2353 return false;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002354 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002355 klass->SetStatus(Class::kStatusError);
2356 klass->NotifyAll();
2357 return false;
2358 }
2359 }
2360 }
2361 return true;
2362}
2363
Brian Carlstrom25c33252011-09-18 15:58:35 -07002364bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002365 CHECK(c != NULL);
2366 if (c->IsInitialized()) {
2367 return true;
2368 }
2369
Elliott Hughes5f791332011-09-15 17:45:30 -07002370 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002371 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Ian Rogers595799e2012-01-11 17:32:51 -08002372 bool success = InitializeClass(c, can_run_clinit);
2373 if (!success) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002374 CHECK(self->IsExceptionPending()) << PrettyClass(c);
Ian Rogers595799e2012-01-11 17:32:51 -08002375 }
2376 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002377}
2378
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002379void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002380 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002381 const ClassLoader* cl = c->GetClassLoader();
2382 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002383 ClassDataItemIterator it(dex_file, class_data);
2384 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2385 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002386 }
2387}
2388
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002389void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002390 size_t num_static_fields = klass->NumStaticFields();
2391 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002392 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002393 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002394 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002395 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002396 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002397 return;
2398 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002399 ClassHelper kh(klass);
2400 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002401 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002402 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002403 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002404
Ian Rogers0571d352011-11-03 19:51:38 -07002405 if (it.HasNext()) {
2406 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2407 std::map<uint32_t, Field*> field_map;
2408 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2409 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2410 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002411 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002412 }
2413}
2414
Ian Rogersc2b44472011-12-14 21:17:17 -08002415bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002416 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002417 if (!LinkSuperClass(klass)) {
2418 return false;
2419 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002420 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002421 return false;
2422 }
2423 if (!LinkInstanceFields(klass)) {
2424 return false;
2425 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002426 if (!LinkStaticFields(klass)) {
2427 return false;
2428 }
2429 CreateReferenceInstanceOffsets(klass);
2430 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002431 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2432 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002433 return true;
2434}
2435
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002436bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002437 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002438 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2439 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
Ian Rogerscab01012012-01-10 17:35:46 -08002440 CHECK(class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002441 uint16_t super_class_idx = class_def->superclass_idx_;
2442 if (super_class_idx != DexFile::kDexNoIndex16) {
2443 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002444 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002445 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002446 return false;
2447 }
Ian Rogersbe125a92012-01-11 15:19:49 -08002448 // Verify
2449 if (!klass->CanAccess(super_class)) {
2450 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2451 "Class %s extended by class %s is inaccessible",
2452 PrettyDescriptor(super_class).c_str(),
2453 PrettyDescriptor(klass.get()).c_str());
2454 return false;
2455 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002456 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002457 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002458 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2459 if (interfaces != NULL) {
2460 for (size_t i = 0; i < interfaces->Size(); i++) {
2461 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2462 Class* interface = ResolveType(dex_file, idx, klass.get());
2463 if (interface == NULL) {
2464 DCHECK(Thread::Current()->IsExceptionPending());
2465 return false;
2466 }
2467 // Verify
2468 if (!klass->CanAccess(interface)) {
2469 // TODO: the RI seemed to ignore this in my testing.
2470 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2471 "Interface %s implemented by class %s is inaccessible",
2472 PrettyDescriptor(interface).c_str(),
2473 PrettyDescriptor(klass.get()).c_str());
2474 return false;
2475 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002476 }
2477 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002478 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002479 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002480 return true;
2481}
2482
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002483bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002484 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002485 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002486 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002487 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002488 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002489 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002490 return false;
2491 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002492 return true;
2493 }
2494 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002495 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002496 return false;
2497 }
2498 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002499 if (super->IsFinal() || super->IsInterface()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002500 Thread* self = Thread::Current();
2501 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002502 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002503 PrettyDescriptor(super).c_str(),
2504 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002505 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002506 return false;
2507 }
2508 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002509 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002510 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002511 PrettyDescriptor(super).c_str(),
2512 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002513 return false;
2514 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002515
2516 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2517 if (super->IsFinalizable()) {
2518 klass->SetFinalizable();
2519 }
2520
Elliott Hughes2da50362011-10-10 16:57:08 -07002521 // Inherit reference flags (if any) from the superclass.
2522 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2523 if (reference_flags != 0) {
2524 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2525 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002526 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002527 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002528 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002529 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002530 return false;
2531 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002532
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002533#ifndef NDEBUG
2534 // Ensure super classes are fully resolved prior to resolving fields..
2535 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002536 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002537 super = super->GetSuperClass();
2538 }
2539#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002540 return true;
2541}
2542
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002543// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002544bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002545 if (klass->IsInterface()) {
2546 // No vtable.
2547 size_t count = klass->NumVirtualMethods();
2548 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002549 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002550 return false;
2551 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002552 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002553 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002554 }
jeffhaobdb76512011-09-07 11:43:16 -07002555 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002556 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002557 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002558 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002559 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002560 }
2561 return true;
2562}
2563
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002564bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002565 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002566 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2567 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002568 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002569 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002570 SirtRef<ObjectArray<Method> > vtable(klass->GetSuperClass()->GetVTable()->CopyOf(max_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002571 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002572 MethodHelper local_mh(NULL, this);
2573 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002574 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002575 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002576 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002577 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002578 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002579 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002580 super_mh.ChangeMethod(super_method);
2581 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002582 // Verify
2583 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002584 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002585 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002586 PrettyDescriptor(klass.get()).c_str(),
2587 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002588 return false;
2589 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002590 vtable->Set(j, local_method);
2591 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002592 break;
2593 }
2594 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002595 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002596 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002597 vtable->Set(actual_count, local_method);
2598 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002599 actual_count += 1;
2600 }
2601 }
2602 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002603 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002604 return false;
2605 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002606 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002607 CHECK_LE(actual_count, max_count);
2608 if (actual_count < max_count) {
Ian Rogers30fab402012-01-23 15:43:46 -08002609 vtable.reset(vtable->CopyOf(actual_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002610 }
Ian Rogers30fab402012-01-23 15:43:46 -08002611 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002612 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002613 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002614 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002615 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002616 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002617 return false;
2618 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002619 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002620 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002621 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2622 vtable->Set(i, virtual_method);
2623 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002624 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002625 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002626 }
2627 return true;
2628}
2629
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002630bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002631 size_t super_ifcount;
2632 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002633 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002634 } else {
2635 super_ifcount = 0;
2636 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002637 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002638 ClassHelper kh(klass.get(), this);
2639 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2640 ifcount += num_interfaces;
2641 for (size_t i = 0; i < num_interfaces; i++) {
2642 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2643 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002644 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002645 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002646 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002647 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002648 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002649 return true;
2650 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002651 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002652 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002653 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2654 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogersb52b01a2012-01-12 17:01:38 -08002655 Class* super_interface = super_iftable->Get(i)->GetInterface();
2656 iftable->Set(i, AllocInterfaceEntry(super_interface));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002657 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002658 }
2659 // Flatten the interface inheritance hierarchy.
2660 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002661 for (size_t i = 0; i < num_interfaces; i++) {
2662 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002663 DCHECK(interface != NULL);
2664 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002665 ClassHelper ih(interface);
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002666 Thread* self = Thread::Current();
2667 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002668 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002669 PrettyDescriptor(klass.get()).c_str(),
2670 PrettyDescriptor(ih.GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002671 return false;
2672 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002673 // Check if interface is already in iftable
2674 bool duplicate = false;
2675 for (size_t j = 0; j < idx; j++) {
2676 Class* existing_interface = iftable->Get(j)->GetInterface();
2677 if (existing_interface == interface) {
2678 duplicate = true;
2679 break;
2680 }
2681 }
2682 if (!duplicate) {
2683 // Add this non-duplicate interface.
2684 iftable->Set(idx++, AllocInterfaceEntry(interface));
2685 // Add this interface's non-duplicate super-interfaces.
2686 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2687 Class* super_interface = interface->GetIfTable()->Get(j)->GetInterface();
2688 bool super_duplicate = false;
2689 for (size_t k = 0; k < idx; k++) {
2690 Class* existing_interface = iftable->Get(k)->GetInterface();
2691 if (existing_interface == super_interface) {
2692 super_duplicate = true;
2693 break;
2694 }
2695 }
2696 if (!super_duplicate) {
2697 iftable->Set(idx++, AllocInterfaceEntry(super_interface));
2698 }
2699 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002700 }
2701 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002702 // Shrink iftable in case duplicates were found
2703 if (idx < ifcount) {
2704 iftable.reset(iftable->CopyOf(idx));
2705 ifcount = idx;
2706 } else {
2707 CHECK_EQ(idx, ifcount);
2708 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002709 klass->SetIfTable(iftable.get());
Elliott Hughes4681c802011-09-25 18:04:37 -07002710
2711 // If we're an interface, we don't need the vtable pointers, so we're done.
2712 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002713 return true;
2714 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002715 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002716 MethodHelper vtable_mh(NULL, this);
2717 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002718 for (size_t i = 0; i < ifcount; ++i) {
2719 InterfaceEntry* interface_entry = iftable->Get(i);
2720 Class* interface = interface_entry->GetInterface();
2721 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2722 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002723 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002724 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2725 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002726 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002727 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002728 // For each method listed in the interface's method list, find the
2729 // matching method in our class's method list. We want to favor the
2730 // subclass over the superclass, which just requires walking
2731 // back from the end of the vtable. (This only matters if the
2732 // superclass defines a private method and this class redefines
2733 // it -- otherwise it would use the same vtable slot. In .dex files
2734 // those don't end up in the virtual method table, so it shouldn't
2735 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002736 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2737 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002738 vtable_mh.ChangeMethod(vtable_method);
2739 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002740 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002741 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002742 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002743 return false;
2744 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002745 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002746 break;
2747 }
2748 }
2749 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002750 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002751 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002752 Method* mir_method = miranda_list[mir];
2753 vtable_mh.ChangeMethod(mir_method);
2754 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002755 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002756 break;
2757 }
2758 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002759 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002760 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002761 miranda_method.reset(AllocMethod());
2762 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2763 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002764 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002765 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002766 }
2767 }
2768 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002769 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002770 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002771 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002772 klass->SetVirtualMethods((old_method_count == 0)
2773 ? AllocObjectArray<Method>(new_method_count)
2774 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002775
Ian Rogers30fab402012-01-23 15:43:46 -08002776 SirtRef<ObjectArray<Method> > vtable(klass->GetVTableDuringLinking());
2777 CHECK(vtable.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002778 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002779 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers30fab402012-01-23 15:43:46 -08002780 vtable.reset(vtable->CopyOf(new_vtable_count));
Elliott Hughes4681c802011-09-25 18:04:37 -07002781 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002782 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002783 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002784 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2785 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2786 klass->SetVirtualMethod(old_method_count + i, method);
2787 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002788 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002789 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002790 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002791 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002792
2793 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2794 for (int i = 0; i < vtable->GetLength(); ++i) {
2795 CHECK(vtable->Get(i) != NULL);
2796 }
2797
2798// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2799
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002800 return true;
2801}
2802
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002803bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2804 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002805 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002806}
2807
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002808bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2809 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002810 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002811 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002812 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002813 return success;
2814}
2815
Brian Carlstromdbc05252011-09-09 01:59:59 -07002816struct LinkFieldsComparator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002817 explicit LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002818 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002819 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002820 fh_->ChangeField(field1);
2821 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2822 fh_->ChangeField(field2);
2823 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002824 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2825 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2826 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2827 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002828 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2829 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2830 if (order1 != order2) {
2831 return order1 < order2;
2832 }
2833
2834 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002835 fh_->ChangeField(field1);
2836 StringPiece name1(fh_->GetName());
2837 fh_->ChangeField(field2);
2838 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002839 return name1 < name2;
2840 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002841
2842 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002843};
2844
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002845bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002846 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002847 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002848
2849 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002850 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002851
2852 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002853 size_t size;
2854 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002855 if (is_static) {
2856 size = klass->GetClassSize();
2857 field_offset = Class::FieldsOffset();
2858 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002859 Class* super_class = klass->GetSuperClass();
2860 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002861 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002862 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002863 }
2864 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002865 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002866
Brian Carlstromdbc05252011-09-09 01:59:59 -07002867 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002868
Brian Carlstromdbc05252011-09-09 01:59:59 -07002869 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002870 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002871 std::deque<Field*> grouped_and_sorted_fields;
2872 for (size_t i = 0; i < num_fields; i++) {
2873 grouped_and_sorted_fields.push_back(fields->Get(i));
2874 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002875 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002876 std::sort(grouped_and_sorted_fields.begin(),
2877 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002878 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002879
2880 // References should be at the front.
2881 size_t current_field = 0;
2882 size_t num_reference_fields = 0;
2883 for (; current_field < num_fields; current_field++) {
2884 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002885 fh.ChangeField(field);
2886 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002887 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002888 if (isPrimitive) {
2889 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002890 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002891 grouped_and_sorted_fields.pop_front();
2892 num_reference_fields++;
2893 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002894 field->SetOffset(field_offset);
2895 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002896 }
2897
2898 // Now we want to pack all of the double-wide fields together. If
2899 // we're not aligned, though, we want to shuffle one 32-bit field
2900 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002901 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002902 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2903 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002904 fh.ChangeField(field);
2905 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002906 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2907 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002908 continue;
2909 }
2910 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002911 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002912 // drop the consumed field
2913 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2914 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002915 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002916 // whether we found a 32-bit field for padding or not, we advance
2917 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002918 }
2919
2920 // Alignment is good, shuffle any double-wide fields forward, and
2921 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002922 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002923 while (!grouped_and_sorted_fields.empty()) {
2924 Field* field = grouped_and_sorted_fields.front();
2925 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002926 fh.ChangeField(field);
2927 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002928 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002929 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002930 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002931 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002932 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002933 ? sizeof(uint64_t)
2934 : sizeof(uint32_t)));
2935 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002936 }
2937
Elliott Hughesadb460d2011-10-05 17:02:34 -07002938 // 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 -08002939 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
2940 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002941 // We know there are no non-reference fields in the Reference classes, and we know
2942 // that 'referent' is alphabetically last, so this is easy...
2943 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002944 fh.ChangeField(fields->Get(num_fields - 1));
Elliott Hughesba8eee12012-01-24 20:25:24 -08002945 CHECK_STREQ(fh.GetName(), "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07002946 --num_reference_fields;
2947 }
2948
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002949#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002950 // Make sure that all reference fields appear before
2951 // non-reference fields, and all double-wide fields are aligned.
2952 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002953 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002954 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002955 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002956 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002957 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002958 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002959 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2960 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002961 fh.ChangeField(field);
2962 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002963 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002964 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002965 is_primitive = true; // We lied above, so we have to expect a lie here.
2966 }
2967 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002968 if (!seen_non_ref) {
2969 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002970 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002971 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002972 } else {
2973 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002974 }
2975 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002976 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002977 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002978 }
2979#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002980 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002981 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002982 if (is_static) {
2983 klass->SetNumReferenceStaticFields(num_reference_fields);
2984 klass->SetClassSize(size);
2985 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002986 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002987 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002988 klass->SetObjectSize(size);
2989 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002990 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002991 return true;
2992}
2993
2994// Set the bitmap of reference offsets, refOffsets, from the ifields
2995// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002996void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002997 uint32_t reference_offsets = 0;
2998 Class* super_class = klass->GetSuperClass();
2999 if (super_class != NULL) {
3000 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003001 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003002 if (reference_offsets == CLASS_WALK_SUPER) {
3003 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003004 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003005 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003006 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003007 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003008}
3009
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003010void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003011 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003012}
3013
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003014void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003015 uint32_t reference_offsets) {
3016 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003017 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
3018 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003019 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003020 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003021 // All of the fields that contain object references are guaranteed
3022 // to be at the beginning of the fields list.
3023 for (size_t i = 0; i < num_reference_fields; ++i) {
3024 // Note that byte_offset is the offset from the beginning of
3025 // object, not the offset into instance data
3026 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003027 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003028 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
3029 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
3030 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07003031 CHECK_NE(new_bit, 0U);
3032 reference_offsets |= new_bit;
3033 } else {
3034 reference_offsets = CLASS_WALK_SUPER;
3035 break;
3036 }
3037 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003038 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003039 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003040 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003041 } else {
3042 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003043 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003044}
3045
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003046String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07003047 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003048 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003049 if (resolved != NULL) {
3050 return resolved;
3051 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003052 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
3053 int32_t utf16_length = dex_file.GetStringLength(string_id);
3054 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07003055 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003056 dex_cache->SetResolvedString(string_idx, string);
3057 return string;
3058}
3059
3060Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003061 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003062 DexCache* dex_cache,
3063 const ClassLoader* class_loader) {
3064 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003065 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07003066 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003067 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003068 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05003069 // TODO: we used to throw here if resolved's class loader was not the
3070 // boot class loader. This was to permit different classes with the
3071 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003072 dex_cache->SetResolvedType(type_idx, resolved);
3073 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08003074 CHECK(Thread::Current()->IsExceptionPending())
3075 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003076 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003077 }
3078 return resolved;
3079}
3080
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003081Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
3082 uint32_t method_idx,
3083 DexCache* dex_cache,
3084 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003085 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003086 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
3087 if (resolved != NULL) {
3088 return resolved;
3089 }
3090 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3091 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
3092 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07003093 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003094 return NULL;
3095 }
3096
Ian Rogers0571d352011-11-03 19:51:38 -07003097 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
3098 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003099 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003100 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003101 } else if (klass->IsInterface()) {
3102 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003103 } else {
3104 resolved = klass->FindVirtualMethod(name, signature);
3105 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003106 if (resolved != NULL) {
3107 dex_cache->SetResolvedMethod(method_idx, resolved);
3108 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003109 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003110 }
3111 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003112}
3113
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003114Field* ClassLinker::ResolveField(const DexFile& dex_file,
3115 uint32_t field_idx,
3116 DexCache* dex_cache,
3117 const ClassLoader* class_loader,
3118 bool is_static) {
3119 Field* resolved = dex_cache->GetResolvedField(field_idx);
3120 if (resolved != NULL) {
3121 return resolved;
3122 }
3123 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3124 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3125 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003126 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003127 return NULL;
3128 }
3129
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003130 const char* name = dex_file.GetFieldName(field_id);
3131 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003132 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003133 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003134 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003135 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003136 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003137 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003138 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003139 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08003140 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
3141 }
3142 return resolved;
3143}
3144
3145Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
3146 uint32_t field_idx,
3147 DexCache* dex_cache,
3148 const ClassLoader* class_loader) {
3149 Field* resolved = dex_cache->GetResolvedField(field_idx);
3150 if (resolved != NULL) {
3151 return resolved;
3152 }
3153 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3154 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3155 if (klass == NULL) {
3156 DCHECK(Thread::Current()->IsExceptionPending());
3157 return NULL;
3158 }
3159
3160 const char* name = dex_file.GetFieldName(field_id);
3161 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3162 resolved = klass->FindField(name, type);
3163 if (resolved != NULL) {
3164 dex_cache->SetResolvedField(field_idx, resolved);
3165 } else {
3166 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003167 }
3168 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07003169}
3170
Ian Rogersad25ac52011-10-04 19:13:33 -07003171const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
3172 Class* declaring_class = referrer->GetDeclaringClass();
3173 DexCache* dex_cache = declaring_class->GetDexCache();
3174 const DexFile& dex_file = FindDexFile(dex_cache);
3175 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3176 return dex_file.GetShorty(method_id.proto_idx_);
3177}
3178
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003179void ClassLinker::DumpAllClasses(int flags) const {
3180 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3181 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3182 std::vector<Class*> all_classes;
3183 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003184 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003185 typedef Table::const_iterator It; // TODO: C++0x auto
3186 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3187 all_classes.push_back(it->second);
3188 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003189 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3190 all_classes.push_back(it->second);
3191 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003192 }
3193
3194 for (size_t i = 0; i < all_classes.size(); ++i) {
3195 all_classes[i]->DumpClass(std::cerr, flags);
3196 }
3197}
3198
Elliott Hughescac6cc72011-11-03 20:31:21 -07003199void ClassLinker::DumpForSigQuit(std::ostream& os) const {
3200 MutexLock mu(classes_lock_);
3201 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3202 << classes_.size() << " allocated classes\n";
3203}
3204
Elliott Hughese27955c2011-08-26 15:21:24 -07003205size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003206 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003207 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003208}
3209
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003210pid_t ClassLinker::GetClassesLockOwner() {
3211 return classes_lock_.GetOwner();
3212}
3213
3214pid_t ClassLinker::GetDexLockOwner() {
3215 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003216}
3217
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003218void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3219 DCHECK(!init_done_);
3220
3221 DCHECK(klass != NULL);
3222 DCHECK(klass->GetClassLoader() == NULL);
3223
3224 DCHECK(class_roots_ != NULL);
3225 DCHECK(class_roots_->Get(class_root) == NULL);
3226 class_roots_->Set(class_root, klass);
3227}
3228
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003229} // namespace art