blob: cf0c09481a15c25ff7313362099e456fcf9d97c1 [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;",
Ian Rogers5167c972012-02-03 10:41:20 -0800189 "Ljava/lang/Throwable;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700190 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700191 "Z",
192 "B",
193 "C",
194 "D",
195 "F",
196 "I",
197 "J",
198 "S",
199 "V",
200 "[Z",
201 "[B",
202 "[C",
203 "[D",
204 "[F",
205 "[I",
206 "[J",
207 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700208 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700209};
210
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800211ClassLinker* ClassLinker::Create(const std::string& boot_class_path, InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700212 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800213 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700214 class_linker->Init(boot_class_path);
215 return class_linker.release();
216}
217
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800218ClassLinker* ClassLinker::Create(InternTable* intern_table) {
219 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700220 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700221 return class_linker.release();
222}
223
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800224ClassLinker::ClassLinker(InternTable* intern_table)
225 : dex_lock_("ClassLinker dex lock"),
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700226 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700227 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700228 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700229 init_done_(false),
230 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700231 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700232}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700233
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700234void CreateClassPath(const std::string& class_path,
235 std::vector<const DexFile*>& class_path_vector) {
236 std::vector<std::string> parsed;
237 Split(class_path, ':', parsed);
238 for (size_t i = 0; i < parsed.size(); ++i) {
239 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700240 if (dex_file == NULL) {
241 LOG(WARNING) << "Failed to open dex file " << parsed[i];
242 } else {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700243 class_path_vector.push_back(dex_file);
244 }
245 }
246}
247
248void ClassLinker::Init(const std::string& boot_class_path) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800249 VLOG(startup) << "ClassLinker::InitFrom entering boot_class_path=" << boot_class_path;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700250
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700251 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700252
Elliott Hughes30646832011-10-13 16:59:46 -0700253 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700254 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
255 CHECK(java_lang_Class.get() != NULL);
256 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700257 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700258 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700259
Elliott Hughes418d20f2011-09-22 14:00:39 -0700260 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700261 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
262 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700263
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700264 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700265 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
266 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700267 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700268 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700269 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700270
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700271 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700272 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
273 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700274
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700275 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700276 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700277
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700278 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700279 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
280 char_array_class->SetComponentType(char_class.get());
281 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700282
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700283 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700284 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
285 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700286 java_lang_String->SetObjectSize(sizeof(String));
287 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400288
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700289 // Create storage for root classes, save away our work so far (requires
290 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700291 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700292 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700293 SetClassRoot(kJavaLangClass, java_lang_Class.get());
294 SetClassRoot(kJavaLangObject, java_lang_Object.get());
295 SetClassRoot(kClassArrayClass, class_array_class.get());
296 SetClassRoot(kObjectArrayClass, object_array_class.get());
297 SetClassRoot(kCharArrayClass, char_array_class.get());
298 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700299
300 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700301 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
302 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
303 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
304 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
305 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
306 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
307 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
308 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700309
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700310 // Create array interface entries to populate once we can load system classes
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700311 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700312
313 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700314 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700315 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700316 IntArray::SetArrayClass(int_array_class.get());
317 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700318
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700319 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700320
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700321 // setup boot_class_path_ and register class_path now that we can
322 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700323 std::vector<const DexFile*> boot_class_path_vector;
324 CreateClassPath(boot_class_path, boot_class_path_vector);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700325 CHECK_NE(0U, boot_class_path_vector.size());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700326 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
327 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700328 CHECK(dex_file != NULL);
329 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700330 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700331
Elliott Hughes80609252011-09-23 17:24:51 -0700332 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700333 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700334 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700335 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700336 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700337 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
338
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700339 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
340 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700341 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700342 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700343 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700344 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700345
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700346 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700347 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700348 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700349 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700350 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700351 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700352
353 // now we can use FindSystemClass
354
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700355 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700356 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700357 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700358
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700359 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700360 java_lang_Object->SetStatus(Class::kStatusNotReady);
361 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700362 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700363 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
364 java_lang_String->SetStatus(Class::kStatusNotReady);
365 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700366 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700367 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
368
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700369 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700370 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
371 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
372
373 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
374 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
375
376 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700377 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700378
379 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
380 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
381
382 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700383 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700384
385 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
386 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
387
388 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
389 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
390
391 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
392 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
393
Elliott Hughes418d20f2011-09-22 14:00:39 -0700394 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700395 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700396
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700397 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700398 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700399
400 // Setup the single, global copies of "interfaces" and "iftable"
401 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
402 CHECK(java_lang_Cloneable != NULL);
403 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
404 CHECK(java_io_Serializable != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700405 // We assume that Cloneable/Serializable don't have superinterfaces --
406 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700407 // supers as well.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800408 array_iftable_->Set(0, AllocInterfaceEntry(java_lang_Cloneable));
409 array_iftable_->Set(1, AllocInterfaceEntry(java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700410
Elliott Hughes418d20f2011-09-22 14:00:39 -0700411 // Sanity check Class[] and Object[]'s interfaces
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800412 ClassHelper kh(class_array_class.get(), this);
413 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
414 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
415 kh.ChangeClass(object_array_class.get());
416 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
417 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
Elliott Hughes80609252011-09-23 17:24:51 -0700418 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700419 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700420 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700421 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700422
Elliott Hughes80609252011-09-23 17:24:51 -0700423 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
424 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700425 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700426
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700427 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700428 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700429 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700430
431 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700432 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700433 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700434
Ian Rogers466bb252011-10-14 03:29:56 -0700435 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
436
437 // Create java.lang.reflect.Proxy root
438 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
439 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
440
Brian Carlstrom1f870082011-08-23 16:02:11 -0700441 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700442 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
443 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700444 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700445 java_lang_ref_FinalizerReference->SetAccessFlags(
446 java_lang_ref_FinalizerReference->GetAccessFlags() |
447 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700448 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700449 java_lang_ref_PhantomReference->SetAccessFlags(
450 java_lang_ref_PhantomReference->GetAccessFlags() |
451 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700452 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700453 java_lang_ref_SoftReference->SetAccessFlags(
454 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700455 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700456 java_lang_ref_WeakReference->SetAccessFlags(
457 java_lang_ref_WeakReference->GetAccessFlags() |
458 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700459
Brian Carlstromaded5f72011-10-07 17:15:04 -0700460 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700461 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700462 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700463 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
464
465 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
466 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
467 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
468
469 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
470 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
471 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
472 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
473
Ian Rogers5167c972012-02-03 10:41:20 -0800474 // Set up java.lang.Throwable and java.lang.StackTraceElement as a convenience
475 SetClassRoot(kJavaLangThrowable, FindSystemClass("Ljava/lang/Throwable;"));
476 Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700477 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
478 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700479 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700480
Brian Carlstroma663ea52011-08-19 23:33:41 -0700481 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700482
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800483 VLOG(startup) << "ClassLinker::InitFrom exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700484}
485
486void ClassLinker::FinishInit() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800487 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700488
489 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700490 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700491 // as the types of the field can't be resolved prior to the runtime being
492 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700493 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700494 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700495 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
496
Elliott Hughesadb460d2011-10-05 17:02:34 -0700497 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
498
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800499 const DexFile& java_lang_dex = FindDexFile(java_lang_ref_Reference->GetDexCache());
500
Brian Carlstrom16192862011-09-12 17:50:06 -0700501 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800502 FieldHelper fh(pendingNext, this);
503 CHECK_STREQ(fh.GetName(), "pendingNext");
504 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
505 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700506
507 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800508 fh.ChangeField(queue);
509 CHECK_STREQ(fh.GetName(), "queue");
510 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
511 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700512
513 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800514 fh.ChangeField(queueNext);
515 CHECK_STREQ(fh.GetName(), "queueNext");
516 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
517 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700518
519 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800520 fh.ChangeField(referent);
521 CHECK_STREQ(fh.GetName(), "referent");
522 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
523 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700524
525 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800526 fh.ChangeField(zombie);
527 CHECK_STREQ(fh.GetName(), "zombie");
528 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
529 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700530
531 Heap::SetReferenceOffsets(referent->GetOffset(),
532 queue->GetOffset(),
533 queueNext->GetOffset(),
534 pendingNext->GetOffset(),
535 zombie->GetOffset());
536
Brian Carlstroma663ea52011-08-19 23:33:41 -0700537 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700538 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700539 ClassRoot class_root = static_cast<ClassRoot>(i);
540 Class* klass = GetClassRoot(class_root);
541 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700542 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700543 // note SetClassRoot does additional validation.
544 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700545 }
546
Elliott Hughes92f14b22011-10-06 12:29:54 -0700547 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700548
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700549 // disable the slow paths in FindClass and CreatePrimitiveClass now
550 // that Object, Class, and Object[] are setup
551 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700552
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800553 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700554}
555
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700556void ClassLinker::RunRootClinits() {
557 Thread* self = Thread::Current();
558 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
559 Class* c = GetClassRoot(ClassRoot(i));
560 if (!c->IsArrayClass() && !c->IsPrimitive()) {
561 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700562 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700563 }
564 }
565}
566
Brian Carlstromd601af82012-01-06 10:15:19 -0800567bool ClassLinker::GenerateOatFile(const std::string& dex_filename,
568 int oat_fd,
569 const std::string& oat_cache_filename) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800570 std::string dex2oat_string("/system/bin/dex2oat");
571#ifndef NDEBUG
572 dex2oat_string += 'd';
573#endif
574 const char* dex2oat = dex2oat_string.c_str();
575
576 const char* class_path = Runtime::Current()->GetClassPath().c_str();
577
578 std::string boot_image_option_string("--boot-image=");
Ian Rogers30fab402012-01-23 15:43:46 -0800579 boot_image_option_string += Heap::GetSpaces()[0]->AsImageSpace()->GetImageFilename();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800580 const char* boot_image_option = boot_image_option_string.c_str();
581
582 std::string dex_file_option_string("--dex-file=");
Brian Carlstromd601af82012-01-06 10:15:19 -0800583 dex_file_option_string += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800584 const char* dex_file_option = dex_file_option_string.c_str();
585
Brian Carlstromd601af82012-01-06 10:15:19 -0800586 std::string oat_fd_option_string("--oat-fd=");
Brian Carlstrom866c8622012-01-06 16:35:13 -0800587 StringAppendF(&oat_fd_option_string, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800588 const char* oat_fd_option = oat_fd_option_string.c_str();
589
590 std::string oat_name_option_string("--oat-name=");
591 oat_name_option_string += oat_cache_filename;
592 const char* oat_name_option = oat_name_option_string.c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800593
jeffhao262bf462011-10-20 18:36:32 -0700594 // fork and exec dex2oat
595 pid_t pid = fork();
596 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800597 // no allocation allowed between fork and exec
Ian Rogers725aee52012-01-11 11:56:56 -0800598
599 // change process groups, so we don't get reaped by ProcessManager
600 setpgid(0, 0);
601
jeffhao10037c82012-01-23 15:06:23 -0800602 VLOG(class_linker) << dex2oat
603 << " --runtime-arg -Xms64m"
604 << " --runtime-arg -Xmx64m"
605 << " --runtime-arg -classpath"
606 << " --runtime-arg " << class_path
607 << " " << boot_image_option
608 << " " << dex_file_option
609 << " " << oat_fd_option
610 << " " << oat_name_option;
611
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800612 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700613 "--runtime-arg", "-Xms64m",
614 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500615 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800616 "--runtime-arg", class_path,
617 boot_image_option,
618 dex_file_option,
Brian Carlstromd601af82012-01-06 10:15:19 -0800619 oat_fd_option,
620 oat_name_option,
jeffhao262bf462011-10-20 18:36:32 -0700621 NULL);
622
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800623 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
Brian Carlstromd601af82012-01-06 10:15:19 -0800624 return false;
jeffhao262bf462011-10-20 18:36:32 -0700625 } else {
626 // wait for dex2oat to finish
627 int status;
628 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
629 if (got_pid != pid) {
630 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
Brian Carlstromd601af82012-01-06 10:15:19 -0800631 return false;
jeffhao262bf462011-10-20 18:36:32 -0700632 }
633 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800634 LOG(ERROR) << dex2oat << " failed with dex-file=" << dex_filename;
635 return false;
jeffhao262bf462011-10-20 18:36:32 -0700636 }
637 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800638 return true;
jeffhao262bf462011-10-20 18:36:32 -0700639}
640
Brian Carlstrom866c8622012-01-06 16:35:13 -0800641void ClassLinker::RegisterOatFile(const OatFile& oat_file) {
642 MutexLock mu(dex_lock_);
643 RegisterOatFileLocked(oat_file);
644}
645
646void ClassLinker::RegisterOatFileLocked(const OatFile& oat_file) {
647 dex_lock_.AssertHeld();
648 oat_files_.push_back(&oat_file);
649}
650
Ian Rogers30fab402012-01-23 15:43:46 -0800651OatFile* ClassLinker::OpenOat(const ImageSpace* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700652 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700653 const Runtime* runtime = Runtime::Current();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700654 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800655 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
656 // check the down cast
657 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700658 std::string oat_filename;
659 oat_filename += runtime->GetHostPrefix();
660 oat_filename += oat_location->ToModifiedUtf8();
Ian Rogers30fab402012-01-23 15:43:46 -0800661 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBegin());
662 VLOG(startup) << "ClassLinker::OpenOat entering oat_filename=" << oat_filename;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700663 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700664 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700665 return NULL;
666 }
667 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
668 uint32_t image_oat_checksum = image_header.GetOatChecksum();
669 if (oat_checksum != image_oat_checksum) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800670 LOG(ERROR) << "Failed to match oat file checksum " << std::hex << oat_checksum
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700671 << " to expected oat checksum " << std::hex << oat_checksum
672 << " in image";
673 return NULL;
674 }
Brian Carlstrom866c8622012-01-06 16:35:13 -0800675 RegisterOatFileLocked(*oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800676 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700677 return oat_file;
678}
679
Brian Carlstromae826982011-11-09 01:33:42 -0800680const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
681 for (size_t i = 0; i < oat_files_.size(); i++) {
682 const OatFile* oat_file = oat_files_[i];
683 DCHECK(oat_file != NULL);
Ian Rogers7fe2c692011-12-06 16:35:59 -0800684 if (oat_file->GetOatDexFile(dex_file.GetLocation(), false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800685 return oat_file;
686 }
687 }
688 return NULL;
689}
690
Brian Carlstromd601af82012-01-06 10:15:19 -0800691class LockedFd {
692 public:
693 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
694 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
695 if (fd == -1) {
696 PLOG(ERROR) << "Failed to open file '" << name << "'";
697 return NULL;
698 }
699 fchmod(fd, mode);
700
701 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
702 // try to lock non-blocking so we can log if we need may need to block
703 int result = flock(fd, LOCK_EX | LOCK_NB);
704 if (result == -1) {
705 LOG(WARNING) << "sleeping while locking file " << name;
706 // retry blocking
707 result = flock(fd, LOCK_EX);
708 }
709 if (result == -1) {
710 PLOG(ERROR) << "Failed to lock file '" << name << "'";
711 close(fd);
712 return NULL;
713 }
714 return new LockedFd(fd);
715 }
716
717 int GetFd() const {
718 return fd_;
719 }
720
721 ~LockedFd() {
722 if (fd_ != -1) {
723 int result = flock(fd_, LOCK_UN);
724 if (result == -1) {
725 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
726 }
727 close(fd_);
728 }
729 }
730
731 private:
732 explicit LockedFd(int fd) : fd_(fd) {}
733
734 int fd_;
735};
736
Brian Carlstromae826982011-11-09 01:33:42 -0800737const OatFile* ClassLinker::FindOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700738 MutexLock mu(dex_lock_);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800739 const OatFile* open_oat_file = FindOpenedOatFileForDexFile(dex_file);
740 if (open_oat_file != NULL) {
741 return open_oat_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800742 }
743
Brian Carlstromd601af82012-01-06 10:15:19 -0800744 std::string oat_filename(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
Brian Carlstrom866c8622012-01-06 16:35:13 -0800745 open_oat_file = FindOpenedOatFileFromOatLocation(oat_filename);
746 if (open_oat_file != NULL) {
747 return open_oat_file;
748 }
749
Brian Carlstromd601af82012-01-06 10:15:19 -0800750 while (true) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800751 UniquePtr<const OatFile> oat_file(FindOatFileFromOatLocation(oat_filename));
752 if (oat_file.get() != NULL) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800753 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
754 if (dex_file.GetHeader().checksum_ == oat_dex_file->GetDexFileChecksum()) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800755 return oat_file.release();
Brian Carlstromd601af82012-01-06 10:15:19 -0800756 }
757 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
758 << " checksum mismatch with " << dex_file.GetLocation() << " --- regenerating";
759 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
760 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
761 }
762 // Fall through...
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700763 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800764 // Try to generate oat file if it wasn't found or was obsolete.
765 // Note we can be racing with another runtime to do this.
766 std::string oat_cache_filename(GetArtCacheFilenameOrDie(oat_filename));
767 UniquePtr<LockedFd> locked_fd(LockedFd::CreateAndLock(oat_cache_filename, 0644));
768 if (locked_fd.get() == NULL) {
769 LOG(ERROR) << "Failed to create and lock oat file " << oat_cache_filename;
770 return NULL;
Elliott Hughes234da572011-11-03 22:13:06 -0700771 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800772 // Check to see if the fd we opened and locked matches the file in
773 // the filesystem. If they don't, then somebody else unlinked ours
774 // and created a new file, and we need to use that one instead. (If
775 // we caught them between the unlink and the create, we'll get an
776 // ENOENT from the file stat.)
777 struct stat fd_stat;
778 int fd_stat_result = fstat(locked_fd->GetFd(), &fd_stat);
779 if (fd_stat_result != 0) {
780 PLOG(ERROR) << "Failed to fstat file descriptor of oat file " << oat_cache_filename;
781 return NULL;
782 }
783 struct stat file_stat;
784 int file_stat_result = stat(oat_cache_filename.c_str(), &file_stat);
785 if (file_stat_result != 0
786 || fd_stat.st_dev != file_stat.st_dev
787 || fd_stat.st_ino != file_stat.st_ino) {
788 LOG(INFO) << "Opened oat file " << oat_cache_filename << " is stale; sleeping and retrying";
789 usleep(250 * 1000); // if something is hosed, don't peg machine
790 continue;
791 }
792
793 // We have the correct file open and locked. If the file size is
794 // zero, then it was just created by us and we can generate its
795 // contents. If not, someone else created it. Either way, we'll
796 // loop to retry opening the file.
797 if (fd_stat.st_size == 0) {
798 bool success = GenerateOatFile(dex_file.GetLocation(),
799 locked_fd->GetFd(),
800 oat_cache_filename);
801 if (!success) {
802 LOG(ERROR) << "Failed to generate oat file " << oat_cache_filename;
803 return NULL;
804 }
805 }
jeffhao262bf462011-10-20 18:36:32 -0700806 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800807 // Not reached
Brian Carlstromaded5f72011-10-07 17:15:04 -0700808}
809
Brian Carlstromae826982011-11-09 01:33:42 -0800810const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700811 for (size_t i = 0; i < oat_files_.size(); i++) {
812 const OatFile* oat_file = oat_files_[i];
813 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800814 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700815 return oat_file;
816 }
817 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700818 return NULL;
819}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700820
Brian Carlstromae826982011-11-09 01:33:42 -0800821const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
jeffhaof6174e82012-01-31 16:14:17 -0800822 MutexLock mu(dex_lock_);
823 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
824 if (oat_file != NULL) {
825 return oat_file;
826 }
827
828 oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700829 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800830 if (oat_location.empty() || oat_location[0] != '/') {
831 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700832 return NULL;
833 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700834
Brian Carlstroma9f19782011-10-13 00:14:47 -0700835 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Elliott Hughes95572412011-12-13 18:14:20 -0800836 std::string cache_location(GetArtCacheFilenameOrDie(oat_location));
Brian Carlstromae826982011-11-09 01:33:42 -0800837 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700838 if (oat_file != NULL) {
839 return oat_file;
840 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700841 oat_file = OatFile::Open(cache_location, "", NULL);
842 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800843 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700844 return NULL;
845 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700846 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700847
Brian Carlstromae826982011-11-09 01:33:42 -0800848 CHECK(oat_file != NULL) << oat_location;
jeffhaof6174e82012-01-31 16:14:17 -0800849 RegisterOatFileLocked(*oat_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700850 return oat_file;
851}
852
jeffhaof6174e82012-01-31 16:14:17 -0800853const DexFile* ClassLinker::FindDexFileFromDexLocation(const std::string& location) {
854 std::string oat_location(OatFile::DexFilenameToOatFilename(location));
855 const OatFile* oat_file = FindOatFileFromOatLocation(oat_location);
856 if (oat_file == NULL) {
857 return NULL;
858 }
859 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location);
860 if (oat_dex_file == NULL) {
861 return NULL;
862 }
863 const DexFile* dex_file = oat_dex_file->OpenDexFile();
864 if (dex_file == NULL) {
865 return NULL;
866 }
867 if (oat_dex_file->GetDexFileChecksum() != dex_file->GetHeader().checksum_) {
868 return NULL;
869 }
870 return dex_file;
871}
872
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700873void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800874 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700875 CHECK(!init_done_);
876
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700877 const std::vector<Space*>& spaces = Heap::GetSpaces();
878 for (size_t i = 0; i < spaces.size(); i++) {
Ian Rogers30fab402012-01-23 15:43:46 -0800879 if (spaces[i]->IsImageSpace()) {
880 ImageSpace* space = spaces[i]->AsImageSpace();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700881 OatFile* oat_file = OpenOat(space);
882 CHECK(oat_file != NULL) << "Failed to open oat file for image";
883 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
884 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
885
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800886 if (i == 0) {
887 // Special case of setting up the String class early so that we can test arbitrary objects
888 // as being Strings or not
Ian Rogers30fab402012-01-23 15:43:46 -0800889 Class* java_lang_String = space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800890 ->AsObjectArray<Class>()->Get(kJavaLangString);
891 String::SetClass(java_lang_String);
892 }
893
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700894 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
895 static_cast<uint32_t>(dex_caches->GetLength()));
896 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700897 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800898 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom89521892011-12-07 22:05:07 -0800899 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
900 const DexFile* dex_file = oat_dex_file->OpenDexFile();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700901 if (dex_file == NULL) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800902 LOG(FATAL) << "Failed to open dex file " << dex_file_location
903 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700904 }
905
Brian Carlstromaded5f72011-10-07 17:15:04 -0700906 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700907
Brian Carlstromdf143242011-10-10 18:05:34 -0700908 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700909 }
910 }
911 }
912
Brian Carlstroma663ea52011-08-19 23:33:41 -0700913 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
914 DCHECK(heap_bitmap != NULL);
915
Brian Carlstroma663ea52011-08-19 23:33:41 -0700916 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700917 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700918
919 // reinit class_roots_
Ian Rogers30fab402012-01-23 15:43:46 -0800920 Object* class_roots_object =
921 spaces[0]->AsImageSpace()->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700922 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700923
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800924 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700925 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
926 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800927 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700928 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700929 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700930 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
931 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
932 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
933 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
934 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
935 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
936 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
937 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700938 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Ian Rogers5167c972012-02-03 10:41:20 -0800939 Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700940 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700941
942 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700943
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800944 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700945}
946
Brian Carlstrom78128a62011-09-15 17:21:19 -0700947void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700948 DCHECK(obj != NULL);
949 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700950 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700951
Elliott Hughesdbb40792011-11-18 17:05:22 -0800952 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700953 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700954 return;
955 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700956 if (obj->IsClass()) {
957 // restore class to ClassLinker::classes_ table
958 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800959 ClassHelper kh(klass, class_linker);
Brian Carlstrom07bb8552012-01-18 22:10:50 -0800960 Class* existing = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
961 DCHECK(existing == NULL) << kh.GetDescriptor();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700962 return;
963 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700964}
965
966// Keep in sync with InitCallback. Anything we visit, we need to
967// reinit references to when reinitializing a ClassLinker from a
968// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700969void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
970 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700971
972 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700973 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700974 }
975
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700976 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700977 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700978 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700979 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700980 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700981 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700982 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700983 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700984
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700985 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700986}
987
Elliott Hughesa2155262011-11-16 16:26:58 -0800988void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
989 MutexLock mu(classes_lock_);
990 typedef Table::const_iterator It; // TODO: C++0x auto
991 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
992 if (!visitor(it->second, arg)) {
993 return;
994 }
995 }
996 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
997 if (!visitor(it->second, arg)) {
998 return;
999 }
1000 }
1001}
1002
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001003ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001004 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001005 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -07001006 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001007 BooleanArray::ResetArrayClass();
1008 ByteArray::ResetArrayClass();
1009 CharArray::ResetArrayClass();
1010 DoubleArray::ResetArrayClass();
1011 FloatArray::ResetArrayClass();
1012 IntArray::ResetArrayClass();
1013 LongArray::ResetArrayClass();
1014 ShortArray::ResetArrayClass();
1015 PathClassLoader::ResetClass();
Ian Rogers5167c972012-02-03 10:41:20 -08001016 Throwable::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001017 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001018 STLDeleteElements(&boot_class_path_);
1019 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001020}
1021
1022DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001023 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
1024 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001025 return NULL;
1026 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001027 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
1028 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001029 return NULL;
1030 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001031 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
1032 if (strings.get() == NULL) {
1033 return NULL;
1034 }
1035 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
1036 if (types.get() == NULL) {
1037 return NULL;
1038 }
1039 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
1040 if (methods.get() == NULL) {
1041 return NULL;
1042 }
1043 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
1044 if (fields.get() == NULL) {
1045 return NULL;
1046 }
1047 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
1048 if (code_and_direct_methods.get() == NULL) {
1049 return NULL;
1050 }
1051 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
1052 if (initialized_static_storage.get() == NULL) {
1053 return NULL;
1054 }
1055
1056 dex_cache->Init(location.get(),
1057 strings.get(),
1058 types.get(),
1059 methods.get(),
1060 fields.get(),
1061 code_and_direct_methods.get(),
1062 initialized_static_storage.get());
1063 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001064}
1065
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001066CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
1067 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -07001068}
1069
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001070InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
1071 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001072 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
1073 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001074 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001075 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001076}
1077
Brian Carlstrom4873d462011-08-21 15:23:39 -07001078Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
1079 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001080 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001081 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001082 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001083 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001084}
1085
Brian Carlstrom4873d462011-08-21 15:23:39 -07001086Class* ClassLinker::AllocClass(size_t class_size) {
1087 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001088}
1089
Jesse Wilson35baaab2011-08-10 16:18:03 -04001090Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001091 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -07001092}
1093
1094Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001095 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001096}
1097
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001098ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
1099 return ObjectArray<StackTraceElement>::Alloc(
1100 GetClassRoot(kJavaLangStackTraceElementArrayClass),
1101 length);
1102}
1103
Brian Carlstromaded5f72011-10-07 17:15:04 -07001104Class* EnsureResolved(Class* klass) {
1105 DCHECK(klass != NULL);
1106 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -07001107 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001108 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001109 ObjectLock lock(klass);
1110 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001111 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001112 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001113 PrettyDescriptor(klass).c_str());
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001114 klass->SetStatus(Class::kStatusError);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001115 return NULL;
1116 }
1117 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001118 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001119 lock.Wait();
1120 }
1121 }
1122 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001123 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001124 return NULL;
1125 }
1126 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001127 CHECK(klass->IsResolved()) << PrettyClass(klass);
1128 CHECK(!self->IsExceptionPending())
1129 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
1130 return klass;
1131}
1132
Elliott Hughesdb7d5e92011-12-16 18:47:37 -08001133Class* ClassLinker::FindSystemClass(const char* descriptor) {
1134 return FindClass(descriptor, NULL);
1135}
1136
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001137Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001138 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001139 Thread* self = Thread::Current();
1140 DCHECK(self != NULL);
1141 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001142 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001143 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1144 // for primitive classes that aren't backed by dex files.
1145 return FindPrimitiveClass(descriptor[0]);
1146 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001147 // Find the class in the loaded classes table.
1148 Class* klass = LookupClass(descriptor, class_loader);
1149 if (klass != NULL) {
1150 return EnsureResolved(klass);
1151 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001152 // Class is not yet loaded.
1153 if (descriptor[0] == '[') {
1154 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001155
Jesse Wilson47daf872011-11-23 11:42:45 -05001156 } else if (class_loader == NULL) {
1157 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1158 if (pair.second != NULL) {
1159 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1160 }
1161
1162 } else if (ClassLoader::UseCompileTimeClassPath()) {
1163 // first try the boot class path
1164 Class* system_class = FindSystemClass(descriptor);
1165 if (system_class != NULL) {
1166 return system_class;
1167 }
1168 CHECK(self->IsExceptionPending());
1169 self->ClearException();
1170
1171 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001172 const std::vector<const DexFile*>& class_path
1173 = ClassLoader::GetCompileTimeClassPath(class_loader);
1174 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001175 if (pair.second != NULL) {
1176 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001177 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001178
1179 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001180 std::string class_name_string(DescriptorToDot(descriptor));
Jesse Wilson47daf872011-11-23 11:42:45 -05001181 ScopedThreadStateChange(self, Thread::kNative);
Elliott Hughes748382f2012-01-26 18:07:38 -08001182 JNIEnv* env = self->GetJniEnv();
Jesse Wilson47daf872011-11-23 11:42:45 -05001183 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1184 CHECK(c.get() != NULL);
1185 // TODO: cache method?
1186 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1187 CHECK(mid != NULL);
1188 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1189 if (class_name_object.get() == NULL) {
1190 return NULL;
1191 }
1192 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
Ian Rogers761bfa82012-01-11 10:14:05 -08001193 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid,
1194 class_name_object.get()));
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001195 if (env->ExceptionCheck()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001196 // If the ClassLoader threw, pass that exception up.
1197 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001198 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001199 // broken loader - throw NPE to be compatible with Dalvik
1200 ThrowNullPointerException("ClassLoader.loadClass returned null for %s",
1201 class_name_string.c_str());
1202 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001203 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08001204 // success, return Class*
Ian Rogers6b0870d2011-12-15 19:38:12 -08001205 return Decode<Class*>(env, result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001206 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001207 }
1208
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001209 ThrowNoClassDefFoundError("Class %s not found", PrintableString(StringPiece(descriptor)).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001210 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001211}
1212
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001213Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001214 const ClassLoader* class_loader,
1215 const DexFile& dex_file,
1216 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001217 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001218 // Load the class from the dex file.
1219 if (!init_done_) {
1220 // finish up init of hand crafted class_roots_
1221 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001222 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001223 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001224 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001225 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001226 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001227 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001228 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001229 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001230 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001231 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001232 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001233 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001234 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001235 }
1236 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001237 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001238 }
1239 klass->SetDexCache(FindDexCache(dex_file));
1240 LoadClass(dex_file, dex_class_def, klass, class_loader);
1241 // Check for a pending exception during load
1242 Thread* self = Thread::Current();
1243 if (self->IsExceptionPending()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001244 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001245 return NULL;
1246 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001247 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001248 klass->SetClinitThreadId(self->GetTid());
1249 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001250 Class* existing = InsertClass(descriptor, klass.get(), false);
1251 if (existing != NULL) {
1252 // We failed to insert because we raced with another thread.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001253 klass->SetClinitThreadId(0);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001254 klass.reset(existing);
1255 return EnsureResolved(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001256 }
1257 // Finish loading (if necessary) by finding parents
1258 CHECK(!klass->IsLoaded());
1259 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1260 // Loading failed.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001261 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001262 lock.NotifyAll();
1263 return NULL;
1264 }
1265 CHECK(klass->IsLoaded());
1266 // Link the class (if necessary)
1267 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001268 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001269 // Linking failed.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001270 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001271 lock.NotifyAll();
1272 return NULL;
1273 }
1274 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001275
1276 /*
1277 * We send CLASS_PREPARE events to the debugger from here. The
1278 * definition of "preparation" is creating the static fields for a
1279 * class and initializing them to the standard default values, but not
1280 * executing any code (that comes later, during "initialization").
1281 *
1282 * We did the static preparation in LinkClass.
1283 *
1284 * The class has been prepared and resolved but possibly not yet verified
1285 * at this point.
1286 */
1287 Dbg::PostClassPrepare(klass.get());
1288
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001289 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001290}
1291
Brian Carlstrom4873d462011-08-21 15:23:39 -07001292// Precomputes size that will be needed for Class, matching LinkStaticFields
1293size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1294 const DexFile::ClassDef& dex_class_def) {
1295 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001296 size_t num_ref = 0;
1297 size_t num_32 = 0;
1298 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001299 if (class_data != NULL) {
1300 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1301 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001302 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001303 char c = descriptor[0];
1304 if (c == 'L' || c == '[') {
1305 num_ref++;
1306 } else if (c == 'J' || c == 'D') {
1307 num_64++;
1308 } else {
1309 num_32++;
1310 }
1311 }
1312 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001313 // start with generic class data
1314 size_t size = sizeof(Class);
1315 // follow with reference fields which must be contiguous at start
1316 size += (num_ref * sizeof(uint32_t));
1317 // if there are 64-bit fields to add, make sure they are aligned
1318 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1319 if (num_32 != 0) {
1320 // use an available 32-bit field for padding
1321 num_32--;
1322 }
1323 size += sizeof(uint32_t); // either way, we are adding a word
1324 DCHECK_EQ(size, RoundUp(size, 8));
1325 }
1326 // tack on any 64-bit fields now that alignment is assured
1327 size += (num_64 * sizeof(uint64_t));
1328 // tack on any remaining 32-bit fields
1329 size += (num_32 * sizeof(uint32_t));
1330 return size;
1331}
1332
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001333void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001334 // Every kind of method should at least get an invoke stub from the oat_method.
1335 // non-abstract methods also get their code pointers.
1336 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001337 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001338
1339 if (method->IsAbstract()) {
1340 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1341 return;
1342 }
1343 if (method->IsNative()) {
1344 // unregistering restores the dlsym lookup stub
1345 method->UnregisterNative();
jeffhao26c0a1a2012-01-17 16:28:33 -08001346 }
1347
1348 if (Runtime::Current()->IsMethodTracingActive()) {
1349#if defined(__arm__)
1350 Trace* tracer = Runtime::Current()->GetTracer();
1351 void* trace_stub = reinterpret_cast<void*>(art_trace_entry_from_code);
1352 tracer->SaveAndUpdateCode(method.get(), trace_stub);
1353#else
1354 UNIMPLEMENTED(WARNING);
1355#endif
Brian Carlstrom92827a52011-10-10 15:50:01 -07001356 }
1357}
1358
Brian Carlstromf615a612011-07-23 12:50:34 -07001359void ClassLinker::LoadClass(const DexFile& dex_file,
1360 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001361 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001362 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001363 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001364 CHECK(klass->GetDexCache() != NULL);
1365 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001366 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001367 CHECK(descriptor != NULL);
1368
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001369 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001370 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001371 // Make sure that none of our runtime-only flags are set.
1372 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001373 klass->SetAccessFlags(access_flags);
1374 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001375 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001376 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001377
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001378 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001379
Ian Rogers0571d352011-11-03 19:51:38 -07001380 // Load fields fields.
1381 const byte* class_data = dex_file.GetClassData(dex_class_def);
1382 if (class_data == NULL) {
1383 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001384 }
Ian Rogers0571d352011-11-03 19:51:38 -07001385 ClassDataItemIterator it(dex_file, class_data);
1386 if (it.NumStaticFields() != 0) {
1387 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1388 }
1389 if (it.NumInstanceFields() != 0) {
1390 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1391 }
1392 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1393 SirtRef<Field> sfield(AllocField());
1394 klass->SetStaticField(i, sfield.get());
1395 LoadField(dex_file, it, klass, sfield);
1396 }
1397 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1398 SirtRef<Field> ifield(AllocField());
1399 klass->SetInstanceField(i, ifield.get());
1400 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001401 }
1402
Brian Carlstromaded5f72011-10-07 17:15:04 -07001403 UniquePtr<const OatFile::OatClass> oat_class;
1404 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001405 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001406 if (oat_file != NULL) {
1407 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1408 if (oat_dex_file != NULL) {
1409 uint32_t class_def_index;
1410 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1411 CHECK(found) << descriptor;
1412 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001413 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001414 }
1415 }
1416 }
Ian Rogers0571d352011-11-03 19:51:38 -07001417 // Load methods.
1418 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001419 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001420 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001421 }
Ian Rogers0571d352011-11-03 19:51:38 -07001422 if (it.NumVirtualMethods() != 0) {
1423 // TODO: append direct methods to class object
1424 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001425 }
Ian Rogers0571d352011-11-03 19:51:38 -07001426 size_t method_index = 0;
1427 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1428 SirtRef<Method> method(AllocMethod());
1429 klass->SetDirectMethod(i, method.get());
1430 LoadMethod(dex_file, it, klass, method);
1431 if (oat_class.get() != NULL) {
1432 LinkCode(method, oat_class.get(), method_index);
1433 }
1434 method_index++;
1435 }
1436 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1437 SirtRef<Method> method(AllocMethod());
1438 klass->SetVirtualMethod(i, method.get());
1439 LoadMethod(dex_file, it, klass, method);
1440 if (oat_class.get() != NULL) {
1441 LinkCode(method, oat_class.get(), method_index);
1442 }
1443 method_index++;
1444 }
1445 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001446}
1447
Ian Rogers0571d352011-11-03 19:51:38 -07001448void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1449 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001450 uint32_t field_idx = it.GetMemberIndex();
1451 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001452 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001453 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001454}
1455
Ian Rogers0571d352011-11-03 19:51:38 -07001456void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1457 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001458 uint32_t method_idx = it.GetMemberIndex();
1459 dst->SetDexMethodIndex(method_idx);
1460 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001461 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001462
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001463
1464 StringPiece method_name(dex_file.GetMethodName(method_id));
1465 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001466 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1467 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001468
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001469 if (method_name == "finalize") {
1470 // Create the prototype for a signature of "()V"
1471 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1472 if (void_string_id != NULL) {
1473 const DexFile::TypeId* void_type_id =
1474 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1475 if (void_type_id != NULL) {
1476 std::vector<uint16_t> no_args;
1477 const DexFile::ProtoId* finalizer_proto =
1478 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1479 if (finalizer_proto != NULL) {
1480 // We have the prototype in the dex file
1481 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1482 klass->SetFinalizable();
1483 } else {
1484 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1485 // The Enum class declares a "final" finalize() method to prevent subclasses from
1486 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1487 // subclasses, so we exclude it here.
1488 // We also want to avoid setting the flag on Object, where we know that finalize() is
1489 // empty.
1490 if (klass_descriptor != "Ljava/lang/Object;" &&
1491 klass_descriptor != "Ljava/lang/Enum;") {
1492 klass->SetFinalizable();
1493 }
1494 }
1495 }
1496 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001497 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001498 }
Ian Rogers0571d352011-11-03 19:51:38 -07001499 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001500 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001501
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001502 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1503 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1504 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1505 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1506 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1507 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001508}
1509
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001510void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001511 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1512 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001513}
1514
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001515void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1516 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001517 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001518 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001519}
1520
Brian Carlstromaded5f72011-10-07 17:15:04 -07001521bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001522 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001523 for (size_t i = 0; i != dex_files_.size(); ++i) {
1524 if (dex_files_[i] == &dex_file) {
1525 return true;
1526 }
1527 }
1528 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001529}
1530
Brian Carlstromaded5f72011-10-07 17:15:04 -07001531bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001532 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001533 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001534}
1535
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001536void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001537 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001538 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001539 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001540 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001541 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001542}
1543
Brian Carlstromaded5f72011-10-07 17:15:04 -07001544void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001545 {
1546 MutexLock mu(dex_lock_);
1547 if (IsDexFileRegisteredLocked(dex_file)) {
1548 return;
1549 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001550 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001551 // Don't alloc while holding the lock, since allocation may need to
1552 // suspend all threads and another thread may need the dex_lock_ to
1553 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001554 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001555 {
1556 MutexLock mu(dex_lock_);
1557 if (IsDexFileRegisteredLocked(dex_file)) {
1558 return;
1559 }
1560 RegisterDexFileLocked(dex_file, dex_cache);
1561 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001562}
1563
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001564void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001565 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001566 RegisterDexFileLocked(dex_file, dex_cache);
1567}
1568
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001569const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001570 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001571 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001572 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1573 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001574 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001575 }
1576 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001577 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001578 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001579}
1580
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001581DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001582 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001583 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001584 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001585 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001586 }
1587 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001588 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001589 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001590}
1591
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001592Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1593 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001594 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001595 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001596 CHECK(primitive_class != NULL);
1597 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001598 primitive_class->SetPrimitiveType(type);
1599 primitive_class->SetStatus(Class::kStatusInitialized);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001600 Class* existing = InsertClass(descriptor, primitive_class, false);
1601 CHECK(existing == NULL) << "InitPrimitiveClass(" << descriptor << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001602 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001603}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001604
Brian Carlstrombe977852011-07-19 14:54:54 -07001605// Create an array class (i.e. the class object for the array, not the
1606// array itself). "descriptor" looks like "[C" or "[[[[B" or
1607// "[Ljava/lang/String;".
1608//
1609// If "descriptor" refers to an array of primitives, look up the
1610// primitive type's internally-generated class object.
1611//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001612// "class_loader" is the class loader of the class that's referring to
1613// us. It's used to ensure that we're looking for the element type in
1614// the right context. It does NOT become the class loader for the
1615// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001616//
1617// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001618Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001619 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001620
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001621 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001622 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001623 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001624 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001625 return NULL;
1626 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001627
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001628 // See if the component type is already loaded. Array classes are
1629 // always associated with the class loader of their underlying
1630 // element type -- an array of Strings goes with the loader for
1631 // java/lang/String -- so we need to look for it there. (The
1632 // caller should have checked for the existence of the class
1633 // before calling here, but they did so with *their* class loader,
1634 // not the component type's loader.)
1635 //
1636 // If we find it, the caller adds "loader" to the class' initiating
1637 // loader list, which should prevent us from going through this again.
1638 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001639 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001640 // are the same, because our caller (FindClass) just did the
1641 // lookup. (Even if we get this wrong we still have correct behavior,
1642 // because we effectively do this lookup again when we add the new
1643 // class to the hash table --- necessary because of possible races with
1644 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001645 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001646 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001647 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001648 return new_class;
1649 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001650 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001651
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001652 // Fill out the fields in the Class.
1653 //
1654 // It is possible to execute some methods against arrays, because
1655 // all arrays are subclasses of java_lang_Object_, so we need to set
1656 // up a vtable. We can just point at the one in java_lang_Object_.
1657 //
1658 // Array classes are simple enough that we don't need to do a full
1659 // link step.
1660
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001661 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001662 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001663 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001664 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001665 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001666 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001667 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001668 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001669 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001670 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001671 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001672 }
1673 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001674 if (new_class.get() == NULL) {
1675 new_class.reset(AllocClass(sizeof(Class)));
1676 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001677 return NULL;
1678 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001679 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001680 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001681 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001682 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001683 new_class->SetSuperClass(java_lang_Object);
1684 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001685 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001686 new_class->SetClassLoader(component_type->GetClassLoader());
1687 new_class->SetStatus(Class::kStatusInitialized);
1688 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001689 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001690
1691
1692 // All arrays have java/lang/Cloneable and java/io/Serializable as
1693 // interfaces. We need to set that up here, so that stuff like
1694 // "instanceof" works right.
1695 //
1696 // Note: The GC could run during the call to FindSystemClass,
1697 // so we need to make sure the class object is GC-valid while we're in
1698 // there. Do this by clearing the interface list so the GC will just
1699 // think that the entries are null.
1700
1701
1702 // Use the single, global copies of "interfaces" and "iftable"
1703 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001704 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001705 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001706
1707 // Inherit access flags from the component type. Arrays can't be
1708 // used as a superclass or interface, so we want to add "final"
1709 // and remove "interface".
1710 //
1711 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001712 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001713 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001714 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1715 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001716
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001717 Class* existing = InsertClass(descriptor, new_class.get(), false);
1718 if (existing == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001719 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001720 }
1721 // Another thread must have loaded the class after we
1722 // started but before we finished. Abandon what we've
1723 // done.
1724 //
1725 // (Yes, this happens.)
1726
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001727 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001728}
1729
1730Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001731 switch (Primitive::GetType(type)) {
1732 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001733 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001734 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001735 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001736 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001737 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001738 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001739 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001740 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001741 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001742 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001743 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001744 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001745 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001746 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001747 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001748 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001749 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001750 case Primitive::kPrimNot:
1751 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001752 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001753 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001754 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001755 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001756}
1757
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001758Class* ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001759 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001760 DexCache* dex_cache = klass->GetDexCache();
1761 std::string source;
1762 if (dex_cache != NULL) {
1763 source += " from ";
1764 source += dex_cache->GetLocation()->ToModifiedUtf8();
1765 }
1766 LOG(INFO) << "Loaded class " << descriptor << source;
1767 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001768 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001769 MutexLock mu(classes_lock_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001770 Table& classes = image_class ? image_classes_ : classes_;
1771 Class* existing = LookupClass(descriptor.data(), klass->GetClassLoader(), hash, classes);
1772#ifndef NDEBUG
1773 // Check we don't have the class in the other table in error
1774 Table& other_classes = image_class ? classes_ : image_classes_;
1775 CHECK(LookupClass(descriptor.data(), klass->GetClassLoader(), hash, other_classes) == NULL);
1776#endif
1777 if (existing != NULL) {
1778 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07001779 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001780 classes.insert(std::make_pair(hash, klass));
1781 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001782}
1783
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001784bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1785 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001786 MutexLock mu(classes_lock_);
Elliott Hughese5448b52012-01-18 16:44:06 -08001787 typedef Table::iterator It; // TODO: C++0x auto
Brian Carlstromae826982011-11-09 01:33:42 -08001788 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001789 ClassHelper kh;
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001790 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001791 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001792 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001793 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001794 classes_.erase(it);
1795 return true;
1796 }
1797 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001798 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001799 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001800 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001801 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001802 image_classes_.erase(it);
1803 return true;
1804 }
1805 }
1806 return false;
1807}
1808
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001809Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1810 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001811 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001812 // TODO: determine if its better to search classes_ or image_classes_ first
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001813 Class* klass = LookupClass(descriptor, class_loader, hash, classes_);
1814 if (klass != NULL) {
1815 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001816 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001817 return LookupClass(descriptor, class_loader, hash, image_classes_);
1818}
1819
1820Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader,
1821 size_t hash, const Table& classes) {
1822 ClassHelper kh(NULL, this);
1823 typedef Table::const_iterator It; // TODO: C++0x auto
1824 for (It it = classes.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001825 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001826 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001827 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001828#ifndef NDEBUG
1829 for (++it; it != end && it->first == hash; ++it) {
1830 kh.ChangeClass(it->second);
1831 CHECK(!(strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader))
1832 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
1833 << PrettyClass(it->second) << " " << it->second << " " << it->second->GetClassLoader();
1834 }
1835#endif
Ian Rogers5d76c432011-10-31 21:42:49 -07001836 return klass;
1837 }
1838 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001839 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001840}
1841
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001842void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001843 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001844 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001845 MutexLock mu(classes_lock_);
1846 typedef Table::const_iterator It; // TODO: C++0x auto
1847 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001848 ClassHelper kh(NULL, this);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001849 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001850 Class* klass = it->second;
1851 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001852 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001853 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001854 }
1855 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001856 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001857 Class* klass = it->second;
1858 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001859 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001860 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001861 }
1862 }
1863}
1864
Ian Rogersc20a83e2012-01-18 18:15:32 -08001865#ifndef NDEBUG
1866static void CheckMethodsHaveGcMaps(Class* klass) {
1867 if (!Runtime::Current()->IsStarted()) {
1868 return;
1869 }
1870 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
1871 Method* method = klass->GetDirectMethod(i);
1872 if (!method->IsNative() && !method->IsAbstract()) {
1873 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1874 }
1875 }
1876 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
1877 Method* method = klass->GetVirtualMethod(i);
1878 if (!method->IsNative() && !method->IsAbstract()) {
1879 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1880 }
1881 }
1882}
1883#else
1884static void CheckMethodsHaveGcMaps(Class* klass) {
1885}
1886#endif
1887
jeffhao98eacac2011-09-14 16:11:53 -07001888void ClassLinker::VerifyClass(Class* klass) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001889 ObjectLock lock(klass);
1890
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001891 // TODO: assert that the monitor on the Class is held
jeffhao98eacac2011-09-14 16:11:53 -07001892 if (klass->IsVerified()) {
1893 return;
1894 }
1895
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001896 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved) << PrettyClass(klass);
jeffhao98eacac2011-09-14 16:11:53 -07001897 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001898
Ian Rogers1c5eb702012-02-01 09:18:34 -08001899 // Verify super class
1900 Class* super = klass->GetSuperClass();
1901 std::string error_msg;
1902 if (super != NULL) {
1903 // Acquire lock to prevent races on verifying the super class
1904 ObjectLock lock(super);
1905
1906 if (!super->IsVerified() && !super->IsErroneous()) {
1907 Runtime::Current()->GetClassLinker()->VerifyClass(super);
1908 }
1909 if (!super->IsVerified()) {
1910 error_msg = "Rejecting class ";
1911 error_msg += PrettyDescriptor(klass);
1912 error_msg += " that attempts to sub-class erroneous class ";
1913 error_msg += PrettyDescriptor(super);
1914 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
1915 Thread* self = Thread::Current();
1916 SirtRef<Throwable> cause(self->GetException());
1917 if (cause.get() != NULL) {
1918 self->ClearException();
1919 }
1920 self->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
1921 if (cause.get() != NULL) {
1922 self->GetException()->SetCause(cause.get());
1923 }
1924 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyDescriptor(klass);
1925 klass->SetStatus(Class::kStatusError);
1926 return;
1927 }
1928 }
1929
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001930 // Try to use verification information from oat file, otherwise do runtime verification
1931 const DexFile& dex_file = FindDexFile(klass->GetDexCache());
Ian Rogers1c5eb702012-02-01 09:18:34 -08001932 if (VerifyClassUsingOatFile(dex_file, klass) ||
1933 verifier::DexVerifier::VerifyClass(klass, error_msg)) {
Ian Rogersc4762272012-02-01 15:55:55 -08001934 DCHECK(!Thread::Current()->IsExceptionPending());
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001935 // Make sure all classes referenced by catch blocks are resolved
1936 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001937 klass->SetStatus(Class::kStatusVerified);
Ian Rogersc20a83e2012-01-18 18:15:32 -08001938 // Sanity check that a verified class has GC maps on all methods
1939 CheckMethodsHaveGcMaps(klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001940 } else {
Ian Rogers09f6b562012-01-31 21:58:52 -08001941 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass)
Ian Rogers1c5eb702012-02-01 09:18:34 -08001942 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
1943 << " because: " << error_msg;
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001944 Thread* self = Thread::Current();
Ian Rogersc4762272012-02-01 15:55:55 -08001945 CHECK(!self->IsExceptionPending());
Ian Rogers1c5eb702012-02-01 09:18:34 -08001946 self->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
1947 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyDescriptor(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001948 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001949 }
jeffhao98eacac2011-09-14 16:11:53 -07001950}
1951
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001952bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, Class* klass) {
1953 if (!Runtime::Current()->IsStarted()) {
1954 return false;
1955 }
1956 if (ClassLoader::UseCompileTimeClassPath()) {
1957 return false;
1958 }
1959 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
1960 if (oat_file == NULL) {
1961 return false;
1962 }
1963 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1964 CHECK(oat_dex_file != NULL) << PrettyClass(klass);
1965 const char* descriptor = ClassHelper(klass).GetDescriptor();
1966 uint32_t class_def_index;
1967 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1968 CHECK(found) << descriptor;
1969 UniquePtr<const OatFile::OatClass> oat_class(oat_dex_file->GetOatClass(class_def_index));
1970 CHECK(oat_class.get() != NULL) << descriptor;
1971 Class::Status status = oat_class->GetStatus();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001972 if (status == Class::kStatusVerified || status == Class::kStatusInitialized) {
1973 return true;
1974 }
Ian Rogersc4762272012-02-01 15:55:55 -08001975 if (status == Class::kStatusError) {
1976 // Compile time verification failed. Compile time verification can fail because we have
1977 // incomplete type information. Consider the following:
1978 // class ... {
1979 // Foo x;
1980 // .... () {
1981 // if (...) {
1982 // v1 gets assigned a type of resolved class Foo
1983 // } else {
1984 // v1 gets assigned a type of unresolved class Bar
1985 // }
1986 // iput x = v1
1987 // } }
1988 // when we merge v1 following the if-the-else it results in Conflict
1989 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
1990 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
1991 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
1992 // at compile time).
1993 return false;
1994 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001995 if (status == Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08001996 // Status is uninitialized if we couldn't determine the status at compile time, for example,
1997 // not loading the class.
1998 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
1999 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002000 return false;
2001 }
2002 LOG(FATAL) << "Unexpected class status: " << status;
2003 return false;
2004}
2005
2006void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, Class* klass) {
2007 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
2008 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
2009 }
2010 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
2011 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
2012 }
2013}
2014
2015void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, Method* method) {
2016 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
2017 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
2018 if (code_item == NULL) {
2019 return; // native or abstract method
2020 }
2021 if (code_item->tries_size_ == 0) {
2022 return; // nothing to process
2023 }
2024 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
2025 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2026 ClassLinker* linker = Runtime::Current()->GetClassLinker();
2027 for (uint32_t idx = 0; idx < handlers_size; idx++) {
2028 CatchHandlerIterator iterator(handlers_ptr);
2029 for (; iterator.HasNext(); iterator.Next()) {
2030 // Ensure exception types are resolved so that they don't need resolution to be delivered,
2031 // unresolved exception types will be ignored by exception delivery
2032 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
2033 Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
2034 if (exception_type == NULL) {
2035 DCHECK(Thread::Current()->IsExceptionPending());
2036 Thread::Current()->ClearException();
2037 }
2038 }
2039 }
2040 handlers_ptr = iterator.EndDataPointer();
2041 }
2042}
2043
Ian Rogersc2b44472011-12-14 21:17:17 -08002044static void CheckProxyConstructor(Method* constructor);
2045static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
2046
Jesse Wilson95caa792011-10-12 18:14:17 -04002047Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002048 ClassLoader* loader, ObjectArray<Method>* methods,
2049 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08002050 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002051 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08002052 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04002053 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002054 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002055 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002056 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002057 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07002058 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002059 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08002060
2061 klass->SetStatus(Class::kStatusIdx);
2062
2063 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
2064
2065 // Create static field that holds throws, instance fields are inherited
2066 klass->SetSFields(AllocObjectArray<Field>(1));
2067 SirtRef<Field> sfield(AllocField());
2068 klass->SetStaticField(0, sfield.get());
2069 sfield->SetDexFieldIndex(-1);
2070 sfield->SetDeclaringClass(klass.get());
2071 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002072
Ian Rogers466bb252011-10-14 03:29:56 -07002073 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04002074 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002075 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04002076
Ian Rogers466bb252011-10-14 03:29:56 -07002077 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04002078 size_t num_virtual_methods = methods->GetLength();
2079 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
2080 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002081 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002082 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04002083 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002084
2085 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
2086 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
2087 DCHECK(!Thread::Current()->IsExceptionPending());
2088
2089 // Link the fields and virtual methods, creating vtable and iftables
2090 if (!LinkClass(klass, interfaces)) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002091 klass->SetStatus(Class::kStatusError);
Jesse Wilson95caa792011-10-12 18:14:17 -04002092 return NULL;
2093 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002094 sfield->SetObject(NULL, throws); // initialize throws field
2095 klass->SetStatus(Class::kStatusInitialized);
2096
2097 // sanity checks
2098#ifndef NDEBUG
2099 bool debug = true;
2100#else
2101 bool debug = false;
2102#endif
2103 if (debug) {
2104 CHECK(klass->GetIFields() == NULL);
2105 CheckProxyConstructor(klass->GetDirectMethod(0));
2106 for (size_t i = 0; i < num_virtual_methods; ++i) {
2107 SirtRef<Method> prototype(methods->Get(i));
2108 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
2109 }
Brian Carlstrom89521892011-12-07 22:05:07 -08002110 std::string throws_field_name("java.lang.Class[][] ");
Ian Rogersc2b44472011-12-14 21:17:17 -08002111 throws_field_name += name->ToModifiedUtf8();
2112 throws_field_name += ".throws";
2113 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
2114
2115 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
2116 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
2117 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002118 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04002119}
2120
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002121std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
2122 DCHECK(proxy_class->IsProxyClass());
2123 String* name = proxy_class->GetName();
2124 DCHECK(name != NULL);
2125 return DotToDescriptor(name->ToModifiedUtf8().c_str());
2126}
2127
2128
2129Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07002130 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07002131 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04002132 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07002133 Method* proxy_constructor = proxy_direct_methods->Get(2);
2134 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
2135 // code_ too)
2136 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
2137 // Make this constructor public and fix the class to be our Proxy version
2138 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002139 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08002140 return constructor;
2141}
2142
2143static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07002144 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002145 MethodHelper mh(constructor);
2146 CHECK_STREQ(mh.GetName(), "<init>");
Elliott Hughesba8eee12012-01-24 20:25:24 -08002147 CHECK_EQ(mh.GetSignature(), std::string("(Ljava/lang/reflect/InvocationHandler;)V"));
Ian Rogers466bb252011-10-14 03:29:56 -07002148 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04002149}
2150
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002151Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
2152 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
2153 // prototype method
2154 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
2155 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07002156 // as necessary
2157 Method* method = down_cast<Method*>(prototype->Clone());
2158
2159 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
2160 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002161 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07002162 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002163
Ian Rogers466bb252011-10-14 03:29:56 -07002164 // At runtime the method looks like a reference and argument saving method, clone the code
2165 // related parameters from this method.
2166 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
2167 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
2168 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
2169 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
2170 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08002171 return method;
2172}
Jesse Wilson95caa792011-10-12 18:14:17 -04002173
Ian Rogersc2b44472011-12-14 21:17:17 -08002174static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07002175 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002176 CHECK(!prototype->IsFinal());
2177 CHECK(method->IsFinal());
2178 CHECK(!method->IsAbstract());
2179 MethodHelper mh(method);
2180 const char* method_name = mh.GetName();
2181 const char* method_shorty = mh.GetShorty();
2182 Class* method_return = mh.GetReturnType();
2183
2184 mh.ChangeMethod(prototype.get());
2185
2186 CHECK_STREQ(mh.GetName(), method_name);
2187 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07002188
2189 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002190 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04002191}
2192
Brian Carlstrom25c33252011-09-18 15:58:35 -07002193bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002194 CHECK(klass->IsResolved() || klass->IsErroneous())
2195 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002196
Carl Shapirob5573532011-07-12 18:22:59 -07002197 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002198
Brian Carlstrom25c33252011-09-18 15:58:35 -07002199 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002200 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002201 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002202 ObjectLock lock(klass);
2203
Brian Carlstromd1422f82011-09-28 11:37:09 -07002204 if (klass->GetStatus() == Class::kStatusInitialized) {
2205 return true;
2206 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002207
Brian Carlstromd1422f82011-09-28 11:37:09 -07002208 if (klass->IsErroneous()) {
2209 ThrowEarlierClassFailure(klass);
2210 return false;
2211 }
2212
2213 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07002214 VerifyClass(klass);
2215 if (klass->GetStatus() != Class::kStatusVerified) {
Ian Rogers595799e2012-01-11 17:32:51 -08002216 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002217 return false;
2218 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002219 }
2220
Brian Carlstrom25c33252011-09-18 15:58:35 -07002221 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
2222 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002223 // if the class has a <clinit> but we can't run it during compilation,
Ian Rogers595799e2012-01-11 17:32:51 -08002224 // don't bother going to kStatusInitializing. We return true to maintain
2225 // the invariant that a false result implies there is a pending exception.
2226 return true;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002227 }
2228
Brian Carlstromd1422f82011-09-28 11:37:09 -07002229 // If the class is kStatusInitializing, either this thread is
2230 // initializing higher up the stack or another thread has beat us
2231 // to initializing and we need to wait. Either way, this
2232 // invocation of InitializeClass will not be responsible for
2233 // running <clinit> and will return.
2234 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002235 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002236 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002237 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002238 return true;
2239 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002240 // No. That's fine. Wait for another thread to finish initializing.
2241 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002242 }
2243
2244 if (!ValidateSuperClassDescriptors(klass)) {
2245 klass->SetStatus(Class::kStatusError);
2246 return false;
2247 }
2248
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002249 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified) << PrettyClass(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002250
Elliott Hughesdcc24742011-09-07 14:02:44 -07002251 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002252 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002253 }
2254
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002255 uint64_t t0 = NanoTime();
2256
Brian Carlstrom25c33252011-09-18 15:58:35 -07002257 if (!InitializeSuperClass(klass, can_run_clinit)) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002258 CHECK(klass->IsErroneous());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002259 return false;
2260 }
2261
2262 InitializeStaticFields(klass);
2263
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002264 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002265 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002266 }
2267
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002268 uint64_t t1 = NanoTime();
2269
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002270 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002271 {
2272 ObjectLock lock(klass);
2273
2274 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002275 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002276 klass->SetStatus(Class::kStatusError);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002277 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002278 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002279 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2280 RuntimeStats* thread_stats = self->GetStats();
2281 ++global_stats->class_init_count;
2282 ++thread_stats->class_init_count;
2283 global_stats->class_init_time_ns += (t1 - t0);
2284 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002285 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002286 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002287 ClassHelper kh(klass);
2288 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002289 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002290 }
2291 lock.NotifyAll();
2292 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002293 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002294}
2295
Brian Carlstromd1422f82011-09-28 11:37:09 -07002296bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
2297 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002298 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002299 lock.Wait();
2300
2301 // When we wake up, repeat the test for init-in-progress. If
2302 // there's an exception pending (only possible if
2303 // "interruptShouldThrow" was set), bail out.
2304 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002305 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002306 klass->SetStatus(Class::kStatusError);
2307 return false;
2308 }
2309 // Spurious wakeup? Go back to waiting.
2310 if (klass->GetStatus() == Class::kStatusInitializing) {
2311 continue;
2312 }
2313 if (klass->IsErroneous()) {
2314 // The caller wants an exception, but it was thrown in a
2315 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002316 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002317 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002318 return false;
2319 }
2320 if (klass->IsInitialized()) {
2321 return true;
2322 }
2323 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2324 }
2325 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2326}
2327
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002328bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2329 if (klass->IsInterface()) {
2330 return true;
2331 }
2332 // begin with the methods local to the superclass
2333 if (klass->HasSuperClass() &&
2334 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2335 const Class* super = klass->GetSuperClass();
Ian Rogers595799e2012-01-11 17:32:51 -08002336 for (int i = super->GetVTable()->GetLength() - 1; i >= 0; --i) {
2337 const Method* method = klass->GetVTable()->Get(i);
2338 if (method != super->GetVTable()->Get(i) &&
2339 !IsSameMethodSignatureInDifferentClassContexts(method, super, klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002340 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2341 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2342 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002343 return false;
2344 }
2345 }
2346 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002347 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2348 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2349 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002350 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2351 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002352 const Method* method = interface_entry->GetMethodArray()->Get(j);
Ian Rogers595799e2012-01-11 17:32:51 -08002353 if (!IsSameMethodSignatureInDifferentClassContexts(method, interface,
2354 method->GetDeclaringClass())) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002355 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2356 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2357 PrettyMethod(method).c_str(),
2358 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002359 return false;
2360 }
2361 }
2362 }
2363 }
2364 return true;
2365}
2366
Ian Rogers595799e2012-01-11 17:32:51 -08002367// Returns true if classes referenced by the signature of the method are the
2368// same classes in klass1 as they are in klass2.
2369bool ClassLinker::IsSameMethodSignatureInDifferentClassContexts(const Method* method,
2370 const Class* klass1,
2371 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002372 if (klass1 == klass2) {
2373 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002374 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002375 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002376 const DexFile::ProtoId& proto_id =
2377 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002378 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2379 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002380 if (descriptor == NULL) {
2381 break;
2382 }
2383 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2384 // Found a non-primitive type.
Ian Rogers595799e2012-01-11 17:32:51 -08002385 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002386 return false;
2387 }
2388 }
2389 }
2390 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002391 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002392 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Ian Rogers595799e2012-01-11 17:32:51 -08002393 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002394 return false;
2395 }
2396 }
2397 return true;
2398}
2399
Ian Rogers595799e2012-01-11 17:32:51 -08002400// Returns true if the descriptor resolves to the same class in the context of klass1 and klass2.
2401bool ClassLinker::IsSameDescriptorInDifferentClassContexts(const char* descriptor,
2402 const Class* klass1,
2403 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002404 CHECK(descriptor != NULL);
2405 CHECK(klass1 != NULL);
2406 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002407 if (klass1 == klass2) {
2408 return true;
2409 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002410 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Ian Rogers595799e2012-01-11 17:32:51 -08002411 if (found1 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002412 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002413 }
Ian Rogers595799e2012-01-11 17:32:51 -08002414 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
2415 if (found2 == NULL) {
2416 Thread::Current()->ClearException();
2417 }
2418 return found1 == found2;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002419}
2420
Brian Carlstrom25c33252011-09-18 15:58:35 -07002421bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002422 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002423 if (!klass->IsInterface() && klass->HasSuperClass()) {
2424 Class* super_class = klass->GetSuperClass();
2425 if (super_class->GetStatus() != Class::kStatusInitialized) {
2426 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002427 Thread* self = Thread::Current();
2428 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002429 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002430 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002431 // TODO: check for a pending exception
2432 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002433 if (!can_run_clinit) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002434 // Don't set status to error when we can't run <clinit>.
2435 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing) << PrettyClass(klass);
2436 klass->SetStatus(Class::kStatusVerified);
2437 return false;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002438 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002439 klass->SetStatus(Class::kStatusError);
2440 klass->NotifyAll();
2441 return false;
2442 }
2443 }
2444 }
2445 return true;
2446}
2447
Brian Carlstrom25c33252011-09-18 15:58:35 -07002448bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002449 CHECK(c != NULL);
2450 if (c->IsInitialized()) {
2451 return true;
2452 }
2453
Elliott Hughes5f791332011-09-15 17:45:30 -07002454 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002455 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Ian Rogers595799e2012-01-11 17:32:51 -08002456 bool success = InitializeClass(c, can_run_clinit);
2457 if (!success) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002458 CHECK(self->IsExceptionPending()) << PrettyClass(c);
Ian Rogers595799e2012-01-11 17:32:51 -08002459 }
2460 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002461}
2462
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002463void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002464 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002465 const ClassLoader* cl = c->GetClassLoader();
2466 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002467 ClassDataItemIterator it(dex_file, class_data);
2468 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2469 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002470 }
2471}
2472
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002473void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002474 size_t num_static_fields = klass->NumStaticFields();
2475 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002476 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002477 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002478 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002479 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002480 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002481 return;
2482 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002483 ClassHelper kh(klass);
2484 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002485 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002486 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002487 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002488
Ian Rogers0571d352011-11-03 19:51:38 -07002489 if (it.HasNext()) {
2490 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2491 std::map<uint32_t, Field*> field_map;
2492 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2493 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2494 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002495 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002496 }
2497}
2498
Ian Rogersc2b44472011-12-14 21:17:17 -08002499bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002500 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002501 if (!LinkSuperClass(klass)) {
2502 return false;
2503 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002504 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002505 return false;
2506 }
2507 if (!LinkInstanceFields(klass)) {
2508 return false;
2509 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002510 if (!LinkStaticFields(klass)) {
2511 return false;
2512 }
2513 CreateReferenceInstanceOffsets(klass);
2514 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002515 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2516 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002517 return true;
2518}
2519
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002520bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002521 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002522 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2523 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
Ian Rogerscab01012012-01-10 17:35:46 -08002524 CHECK(class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002525 uint16_t super_class_idx = class_def->superclass_idx_;
2526 if (super_class_idx != DexFile::kDexNoIndex16) {
2527 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002528 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002529 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002530 return false;
2531 }
Ian Rogersbe125a92012-01-11 15:19:49 -08002532 // Verify
2533 if (!klass->CanAccess(super_class)) {
2534 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2535 "Class %s extended by class %s is inaccessible",
2536 PrettyDescriptor(super_class).c_str(),
2537 PrettyDescriptor(klass.get()).c_str());
2538 return false;
2539 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002540 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002541 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002542 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2543 if (interfaces != NULL) {
2544 for (size_t i = 0; i < interfaces->Size(); i++) {
2545 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2546 Class* interface = ResolveType(dex_file, idx, klass.get());
2547 if (interface == NULL) {
2548 DCHECK(Thread::Current()->IsExceptionPending());
2549 return false;
2550 }
2551 // Verify
2552 if (!klass->CanAccess(interface)) {
2553 // TODO: the RI seemed to ignore this in my testing.
2554 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2555 "Interface %s implemented by class %s is inaccessible",
2556 PrettyDescriptor(interface).c_str(),
2557 PrettyDescriptor(klass.get()).c_str());
2558 return false;
2559 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002560 }
2561 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002562 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002563 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002564 return true;
2565}
2566
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002567bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002568 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002569 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002570 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002571 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002572 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002573 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002574 return false;
2575 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002576 return true;
2577 }
2578 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002579 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002580 return false;
2581 }
2582 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002583 if (super->IsFinal() || super->IsInterface()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002584 Thread* self = Thread::Current();
2585 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002586 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002587 PrettyDescriptor(super).c_str(),
2588 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002589 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002590 return false;
2591 }
2592 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002593 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002594 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002595 PrettyDescriptor(super).c_str(),
2596 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002597 return false;
2598 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002599
2600 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2601 if (super->IsFinalizable()) {
2602 klass->SetFinalizable();
2603 }
2604
Elliott Hughes2da50362011-10-10 16:57:08 -07002605 // Inherit reference flags (if any) from the superclass.
2606 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2607 if (reference_flags != 0) {
2608 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2609 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002610 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002611 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002612 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002613 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002614 return false;
2615 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002616
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002617#ifndef NDEBUG
2618 // Ensure super classes are fully resolved prior to resolving fields..
2619 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002620 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002621 super = super->GetSuperClass();
2622 }
2623#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002624 return true;
2625}
2626
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002627// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002628bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002629 if (klass->IsInterface()) {
2630 // No vtable.
2631 size_t count = klass->NumVirtualMethods();
2632 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002633 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002634 return false;
2635 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002636 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002637 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002638 }
jeffhaobdb76512011-09-07 11:43:16 -07002639 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002640 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002641 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002642 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002643 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002644 }
2645 return true;
2646}
2647
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002648bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002649 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002650 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2651 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002652 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002653 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002654 SirtRef<ObjectArray<Method> > vtable(klass->GetSuperClass()->GetVTable()->CopyOf(max_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002655 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002656 MethodHelper local_mh(NULL, this);
2657 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002658 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002659 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002660 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002661 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002662 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002663 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002664 super_mh.ChangeMethod(super_method);
2665 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002666 // Verify
2667 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002668 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002669 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002670 PrettyDescriptor(klass.get()).c_str(),
2671 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002672 return false;
2673 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002674 vtable->Set(j, local_method);
2675 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002676 break;
2677 }
2678 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002679 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002680 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002681 vtable->Set(actual_count, local_method);
2682 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002683 actual_count += 1;
2684 }
2685 }
2686 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002687 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002688 return false;
2689 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002690 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002691 CHECK_LE(actual_count, max_count);
2692 if (actual_count < max_count) {
Ian Rogers30fab402012-01-23 15:43:46 -08002693 vtable.reset(vtable->CopyOf(actual_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002694 }
Ian Rogers30fab402012-01-23 15:43:46 -08002695 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002696 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002697 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002698 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002699 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002700 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002701 return false;
2702 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002703 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002704 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002705 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2706 vtable->Set(i, virtual_method);
2707 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002708 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002709 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002710 }
2711 return true;
2712}
2713
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002714bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002715 size_t super_ifcount;
2716 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002717 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002718 } else {
2719 super_ifcount = 0;
2720 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002721 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002722 ClassHelper kh(klass.get(), this);
2723 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2724 ifcount += num_interfaces;
2725 for (size_t i = 0; i < num_interfaces; i++) {
2726 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2727 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002728 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002729 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002730 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002731 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002732 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002733 return true;
2734 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002735 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002736 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002737 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2738 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogersb52b01a2012-01-12 17:01:38 -08002739 Class* super_interface = super_iftable->Get(i)->GetInterface();
2740 iftable->Set(i, AllocInterfaceEntry(super_interface));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002741 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002742 }
2743 // Flatten the interface inheritance hierarchy.
2744 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002745 for (size_t i = 0; i < num_interfaces; i++) {
2746 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002747 DCHECK(interface != NULL);
2748 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002749 ClassHelper ih(interface);
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002750 Thread* self = Thread::Current();
2751 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002752 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002753 PrettyDescriptor(klass.get()).c_str(),
2754 PrettyDescriptor(ih.GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002755 return false;
2756 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002757 // Check if interface is already in iftable
2758 bool duplicate = false;
2759 for (size_t j = 0; j < idx; j++) {
2760 Class* existing_interface = iftable->Get(j)->GetInterface();
2761 if (existing_interface == interface) {
2762 duplicate = true;
2763 break;
2764 }
2765 }
2766 if (!duplicate) {
2767 // Add this non-duplicate interface.
2768 iftable->Set(idx++, AllocInterfaceEntry(interface));
2769 // Add this interface's non-duplicate super-interfaces.
2770 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2771 Class* super_interface = interface->GetIfTable()->Get(j)->GetInterface();
2772 bool super_duplicate = false;
2773 for (size_t k = 0; k < idx; k++) {
2774 Class* existing_interface = iftable->Get(k)->GetInterface();
2775 if (existing_interface == super_interface) {
2776 super_duplicate = true;
2777 break;
2778 }
2779 }
2780 if (!super_duplicate) {
2781 iftable->Set(idx++, AllocInterfaceEntry(super_interface));
2782 }
2783 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002784 }
2785 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002786 // Shrink iftable in case duplicates were found
2787 if (idx < ifcount) {
2788 iftable.reset(iftable->CopyOf(idx));
2789 ifcount = idx;
2790 } else {
2791 CHECK_EQ(idx, ifcount);
2792 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002793 klass->SetIfTable(iftable.get());
Elliott Hughes4681c802011-09-25 18:04:37 -07002794
2795 // If we're an interface, we don't need the vtable pointers, so we're done.
2796 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002797 return true;
2798 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002799 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002800 MethodHelper vtable_mh(NULL, this);
2801 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002802 for (size_t i = 0; i < ifcount; ++i) {
2803 InterfaceEntry* interface_entry = iftable->Get(i);
2804 Class* interface = interface_entry->GetInterface();
2805 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2806 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002807 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002808 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2809 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002810 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002811 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002812 // For each method listed in the interface's method list, find the
2813 // matching method in our class's method list. We want to favor the
2814 // subclass over the superclass, which just requires walking
2815 // back from the end of the vtable. (This only matters if the
2816 // superclass defines a private method and this class redefines
2817 // it -- otherwise it would use the same vtable slot. In .dex files
2818 // those don't end up in the virtual method table, so it shouldn't
2819 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002820 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2821 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002822 vtable_mh.ChangeMethod(vtable_method);
2823 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002824 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002825 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002826 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002827 return false;
2828 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002829 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002830 break;
2831 }
2832 }
2833 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002834 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002835 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002836 Method* mir_method = miranda_list[mir];
2837 vtable_mh.ChangeMethod(mir_method);
2838 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002839 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002840 break;
2841 }
2842 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002843 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002844 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002845 miranda_method.reset(AllocMethod());
2846 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2847 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002848 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002849 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002850 }
2851 }
2852 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002853 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002854 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002855 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002856 klass->SetVirtualMethods((old_method_count == 0)
2857 ? AllocObjectArray<Method>(new_method_count)
2858 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002859
Ian Rogers30fab402012-01-23 15:43:46 -08002860 SirtRef<ObjectArray<Method> > vtable(klass->GetVTableDuringLinking());
2861 CHECK(vtable.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002862 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002863 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers30fab402012-01-23 15:43:46 -08002864 vtable.reset(vtable->CopyOf(new_vtable_count));
Elliott Hughes4681c802011-09-25 18:04:37 -07002865 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002866 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002867 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002868 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2869 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2870 klass->SetVirtualMethod(old_method_count + i, method);
2871 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002872 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002873 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002874 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002875 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002876
2877 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2878 for (int i = 0; i < vtable->GetLength(); ++i) {
2879 CHECK(vtable->Get(i) != NULL);
2880 }
2881
2882// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2883
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002884 return true;
2885}
2886
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002887bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2888 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002889 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002890}
2891
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002892bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2893 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002894 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002895 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002896 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002897 return success;
2898}
2899
Brian Carlstromdbc05252011-09-09 01:59:59 -07002900struct LinkFieldsComparator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002901 explicit LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002902 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002903 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002904 fh_->ChangeField(field1);
2905 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2906 fh_->ChangeField(field2);
2907 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002908 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2909 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2910 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2911 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002912 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2913 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2914 if (order1 != order2) {
2915 return order1 < order2;
2916 }
2917
2918 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002919 fh_->ChangeField(field1);
2920 StringPiece name1(fh_->GetName());
2921 fh_->ChangeField(field2);
2922 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002923 return name1 < name2;
2924 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002925
2926 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002927};
2928
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002929bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002930 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002931 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002932
2933 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002934 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002935
2936 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002937 size_t size;
2938 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002939 if (is_static) {
2940 size = klass->GetClassSize();
2941 field_offset = Class::FieldsOffset();
2942 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002943 Class* super_class = klass->GetSuperClass();
2944 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002945 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002946 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002947 }
2948 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002949 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002950
Brian Carlstromdbc05252011-09-09 01:59:59 -07002951 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002952
Brian Carlstromdbc05252011-09-09 01:59:59 -07002953 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002954 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002955 std::deque<Field*> grouped_and_sorted_fields;
2956 for (size_t i = 0; i < num_fields; i++) {
2957 grouped_and_sorted_fields.push_back(fields->Get(i));
2958 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002959 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002960 std::sort(grouped_and_sorted_fields.begin(),
2961 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002962 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002963
2964 // References should be at the front.
2965 size_t current_field = 0;
2966 size_t num_reference_fields = 0;
2967 for (; current_field < num_fields; current_field++) {
2968 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002969 fh.ChangeField(field);
2970 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002971 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002972 if (isPrimitive) {
2973 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002974 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002975 grouped_and_sorted_fields.pop_front();
2976 num_reference_fields++;
2977 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002978 field->SetOffset(field_offset);
2979 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002980 }
2981
2982 // Now we want to pack all of the double-wide fields together. If
2983 // we're not aligned, though, we want to shuffle one 32-bit field
2984 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002985 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002986 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2987 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002988 fh.ChangeField(field);
2989 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002990 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2991 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002992 continue;
2993 }
2994 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002995 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002996 // drop the consumed field
2997 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2998 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002999 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07003000 // whether we found a 32-bit field for padding or not, we advance
3001 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003002 }
3003
3004 // Alignment is good, shuffle any double-wide fields forward, and
3005 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07003006 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07003007 while (!grouped_and_sorted_fields.empty()) {
3008 Field* field = grouped_and_sorted_fields.front();
3009 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003010 fh.ChangeField(field);
3011 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003012 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07003013 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003014 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003015 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003016 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07003017 ? sizeof(uint64_t)
3018 : sizeof(uint32_t)));
3019 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003020 }
3021
Elliott Hughesadb460d2011-10-05 17:02:34 -07003022 // 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 -08003023 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
3024 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07003025 // We know there are no non-reference fields in the Reference classes, and we know
3026 // that 'referent' is alphabetically last, so this is easy...
3027 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003028 fh.ChangeField(fields->Get(num_fields - 1));
Elliott Hughesba8eee12012-01-24 20:25:24 -08003029 CHECK_STREQ(fh.GetName(), "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07003030 --num_reference_fields;
3031 }
3032
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003033#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07003034 // Make sure that all reference fields appear before
3035 // non-reference fields, and all double-wide fields are aligned.
3036 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07003037 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003038 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003039 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003040 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003041 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07003042 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07003043 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
3044 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003045 fh.ChangeField(field);
3046 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003047 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003048 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07003049 is_primitive = true; // We lied above, so we have to expect a lie here.
3050 }
3051 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07003052 if (!seen_non_ref) {
3053 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003054 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003055 }
Brian Carlstrombe977852011-07-19 14:54:54 -07003056 } else {
3057 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003058 }
3059 }
Brian Carlstrombe977852011-07-19 14:54:54 -07003060 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003061 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003062 }
3063#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003064 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003065 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003066 if (is_static) {
3067 klass->SetNumReferenceStaticFields(num_reference_fields);
3068 klass->SetClassSize(size);
3069 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003070 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003071 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003072 klass->SetObjectSize(size);
3073 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003074 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003075 return true;
3076}
3077
3078// Set the bitmap of reference offsets, refOffsets, from the ifields
3079// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003080void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003081 uint32_t reference_offsets = 0;
3082 Class* super_class = klass->GetSuperClass();
3083 if (super_class != NULL) {
3084 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003085 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003086 if (reference_offsets == CLASS_WALK_SUPER) {
3087 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003088 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003089 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003090 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003091 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003092}
3093
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003094void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003095 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003096}
3097
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003098void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003099 uint32_t reference_offsets) {
3100 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003101 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
3102 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003103 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003104 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003105 // All of the fields that contain object references are guaranteed
3106 // to be at the beginning of the fields list.
3107 for (size_t i = 0; i < num_reference_fields; ++i) {
3108 // Note that byte_offset is the offset from the beginning of
3109 // object, not the offset into instance data
3110 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003111 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003112 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
3113 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
3114 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07003115 CHECK_NE(new_bit, 0U);
3116 reference_offsets |= new_bit;
3117 } else {
3118 reference_offsets = CLASS_WALK_SUPER;
3119 break;
3120 }
3121 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003122 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003123 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003124 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003125 } else {
3126 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003127 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003128}
3129
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003130String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07003131 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003132 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003133 if (resolved != NULL) {
3134 return resolved;
3135 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003136 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
3137 int32_t utf16_length = dex_file.GetStringLength(string_id);
3138 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07003139 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003140 dex_cache->SetResolvedString(string_idx, string);
3141 return string;
3142}
3143
3144Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003145 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003146 DexCache* dex_cache,
3147 const ClassLoader* class_loader) {
3148 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003149 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07003150 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003151 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003152 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05003153 // TODO: we used to throw here if resolved's class loader was not the
3154 // boot class loader. This was to permit different classes with the
3155 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003156 dex_cache->SetResolvedType(type_idx, resolved);
3157 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08003158 CHECK(Thread::Current()->IsExceptionPending())
3159 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003160 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003161 }
3162 return resolved;
3163}
3164
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003165Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
3166 uint32_t method_idx,
3167 DexCache* dex_cache,
3168 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003169 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003170 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
3171 if (resolved != NULL) {
3172 return resolved;
3173 }
3174 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3175 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
3176 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07003177 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003178 return NULL;
3179 }
3180
Ian Rogers0571d352011-11-03 19:51:38 -07003181 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
3182 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003183 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003184 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003185 } else if (klass->IsInterface()) {
3186 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003187 } else {
3188 resolved = klass->FindVirtualMethod(name, signature);
3189 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003190 if (resolved != NULL) {
3191 dex_cache->SetResolvedMethod(method_idx, resolved);
3192 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003193 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003194 }
3195 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003196}
3197
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003198Field* ClassLinker::ResolveField(const DexFile& dex_file,
3199 uint32_t field_idx,
3200 DexCache* dex_cache,
3201 const ClassLoader* class_loader,
3202 bool is_static) {
3203 Field* resolved = dex_cache->GetResolvedField(field_idx);
3204 if (resolved != NULL) {
3205 return resolved;
3206 }
3207 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3208 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3209 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003210 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003211 return NULL;
3212 }
3213
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003214 const char* name = dex_file.GetFieldName(field_id);
3215 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003216 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003217 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003218 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003219 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003220 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003221 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003222 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003223 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08003224 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
3225 }
3226 return resolved;
3227}
3228
3229Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
3230 uint32_t field_idx,
3231 DexCache* dex_cache,
3232 const ClassLoader* class_loader) {
3233 Field* resolved = dex_cache->GetResolvedField(field_idx);
3234 if (resolved != NULL) {
3235 return resolved;
3236 }
3237 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3238 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3239 if (klass == NULL) {
3240 DCHECK(Thread::Current()->IsExceptionPending());
3241 return NULL;
3242 }
3243
3244 const char* name = dex_file.GetFieldName(field_id);
3245 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3246 resolved = klass->FindField(name, type);
3247 if (resolved != NULL) {
3248 dex_cache->SetResolvedField(field_idx, resolved);
3249 } else {
3250 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003251 }
3252 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07003253}
3254
Ian Rogersad25ac52011-10-04 19:13:33 -07003255const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
3256 Class* declaring_class = referrer->GetDeclaringClass();
3257 DexCache* dex_cache = declaring_class->GetDexCache();
3258 const DexFile& dex_file = FindDexFile(dex_cache);
3259 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3260 return dex_file.GetShorty(method_id.proto_idx_);
3261}
3262
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003263void ClassLinker::DumpAllClasses(int flags) const {
3264 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3265 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3266 std::vector<Class*> all_classes;
3267 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003268 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003269 typedef Table::const_iterator It; // TODO: C++0x auto
3270 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3271 all_classes.push_back(it->second);
3272 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003273 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3274 all_classes.push_back(it->second);
3275 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003276 }
3277
3278 for (size_t i = 0; i < all_classes.size(); ++i) {
3279 all_classes[i]->DumpClass(std::cerr, flags);
3280 }
3281}
3282
Elliott Hughescac6cc72011-11-03 20:31:21 -07003283void ClassLinker::DumpForSigQuit(std::ostream& os) const {
3284 MutexLock mu(classes_lock_);
3285 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3286 << classes_.size() << " allocated classes\n";
3287}
3288
Elliott Hughese27955c2011-08-26 15:21:24 -07003289size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003290 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003291 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003292}
3293
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003294pid_t ClassLinker::GetClassesLockOwner() {
3295 return classes_lock_.GetOwner();
3296}
3297
3298pid_t ClassLinker::GetDexLockOwner() {
3299 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003300}
3301
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003302void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3303 DCHECK(!init_done_);
3304
3305 DCHECK(klass != NULL);
3306 DCHECK(klass->GetClassLoader() == NULL);
3307
3308 DCHECK(class_roots_ != NULL);
3309 DCHECK(class_roots_->Get(class_root) == NULL);
3310 class_roots_->Set(class_root, klass);
3311}
3312
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003313} // namespace art