blob: 32082d39bc51d65cd5457e88053f6e004428f433 [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 Carlstrom5b332c82012-02-01 15:02:31 -080043#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070044#include "runtime.h"
Ian Rogers466bb252011-10-14 03:29:56 -070045#include "runtime_support.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070046#include "ScopedLocalRef.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070047#include "space.h"
Brian Carlstrom40381fb2011-10-19 14:13:40 -070048#include "stack_indirect_reference_table.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070049#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070050#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070051#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070052#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070053
54namespace art {
55
Elliott Hughes4a2b4172011-09-20 17:08:25 -070056namespace {
57
Elliott Hughes362f9bc2011-10-17 18:56:41 -070058void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070059void ThrowNoClassDefFoundError(const char* fmt, ...) {
60 va_list args;
61 va_start(args, fmt);
62 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
63 va_end(args);
64}
65
Elliott Hughes362f9bc2011-10-17 18:56:41 -070066void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughese555dc02011-09-25 10:46:35 -070067void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070068 va_list args;
69 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070070 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070071 va_end(args);
72}
73
Elliott Hughes362f9bc2011-10-17 18:56:41 -070074void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070075void ThrowLinkageError(const char* fmt, ...) {
76 va_list args;
77 va_start(args, fmt);
78 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
79 va_end(args);
80}
81
Ian Rogers9f1ab122011-12-12 08:52:43 -080082void ThrowNoSuchMethodError(bool is_direct, Class* c, const StringPiece& name,
83 const StringPiece& signature) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080084 ClassHelper kh(c);
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070085 std::ostringstream msg;
Ian Rogers9f1ab122011-12-12 08:52:43 -080086 msg << "no " << (is_direct ? "direct" : "virtual") << " method " << name << "." << signature
87 << " in class " << kh.GetDescriptor() << " or its superclasses";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080088 std::string location(kh.GetLocation());
89 if (!location.empty()) {
90 msg << " (defined in " << location << ")";
Elliott Hughescc5f9a92011-09-28 19:17:29 -070091 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070092 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070093}
94
Ian Rogersb067ac22011-12-13 18:05:09 -080095void ThrowNoSuchFieldError(const StringPiece& scope, Class* c, const StringPiece& type,
Ian Rogers9f1ab122011-12-12 08:52:43 -080096 const StringPiece& name) {
97 ClassHelper kh(c);
98 std::ostringstream msg;
Ian Rogersb067ac22011-12-13 18:05:09 -080099 msg << "no " << scope << "field " << name << " of type " << type
Ian Rogers9f1ab122011-12-12 08:52:43 -0800100 << " in class " << kh.GetDescriptor() << " or its superclasses";
101 std::string location(kh.GetLocation());
102 if (!location.empty()) {
103 msg << " (defined in " << location << ")";
104 }
105 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchFieldError;", msg.str().c_str());
106}
107
Ian Rogerscab01012012-01-10 17:35:46 -0800108void ThrowNullPointerException(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
109void ThrowNullPointerException(const char* fmt, ...) {
110 va_list args;
111 va_start(args, fmt);
112 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NullPointerException;", fmt, args);
113 va_end(args);
114}
115
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700116void ThrowEarlierClassFailure(Class* c) {
117 /*
118 * The class failed to initialize on a previous attempt, so we want to throw
119 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
120 * failed in verification, in which case v2 5.4.1 says we need to re-throw
121 * the previous error.
122 */
123 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
124
Brian Carlstrom4d9716c2012-01-30 01:49:33 -0800125 CHECK(c->IsErroneous()) << PrettyClass(c);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700126 if (c->GetVerifyErrorClass() != NULL) {
127 // TODO: change the verifier to store an _instance_, with a useful detail message?
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800128 ClassHelper ve_ch(c->GetVerifyErrorClass());
129 std::string error_descriptor(ve_ch.GetDescriptor());
130 Thread::Current()->ThrowNewException(error_descriptor.c_str(), PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700131 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800132 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700133 }
134}
135
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700136void WrapExceptionInInitializer() {
137 JNIEnv* env = Thread::Current()->GetJniEnv();
138
139 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
140 CHECK(cause.get() != NULL);
141
142 env->ExceptionClear();
143
144 // TODO: add java.lang.Error to JniConstants?
145 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
146 CHECK(error_class.get() != NULL);
147 if (env->IsInstanceOf(cause.get(), error_class.get())) {
148 // We only wrap non-Error exceptions; an Error can just be used as-is.
149 env->Throw(cause.get());
150 return;
151 }
152
153 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
154 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
155 CHECK(eiie_class.get() != NULL);
156
157 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
158 CHECK(mid != NULL);
159
160 ScopedLocalRef<jthrowable> eiie(env,
161 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
162 env->Throw(eiie.get());
163}
164
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800165static size_t Hash(const char* s) {
166 // This is the java.lang.String hashcode for convenience, not interoperability.
167 size_t hash = 0;
168 for (; *s != '\0'; ++s) {
169 hash = hash * 31 + *s;
170 }
171 return hash;
172}
173
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700174} // namespace
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700175
Elliott Hughes418d20f2011-09-22 14:00:39 -0700176const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700177 "Ljava/lang/Class;",
178 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700179 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700180 "[Ljava/lang/Object;",
181 "Ljava/lang/String;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700182 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700183 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700184 "Ljava/lang/reflect/Field;",
185 "Ljava/lang/reflect/Method;",
Ian Rogers466bb252011-10-14 03:29:56 -0700186 "Ljava/lang/reflect/Proxy;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700187 "Ljava/lang/ClassLoader;",
188 "Ldalvik/system/BaseDexClassLoader;",
189 "Ldalvik/system/PathClassLoader;",
Ian Rogers5167c972012-02-03 10:41:20 -0800190 "Ljava/lang/Throwable;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700191 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700192 "Z",
193 "B",
194 "C",
195 "D",
196 "F",
197 "I",
198 "J",
199 "S",
200 "V",
201 "[Z",
202 "[B",
203 "[C",
204 "[D",
205 "[F",
206 "[I",
207 "[J",
208 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700209 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700210};
211
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800212ClassLinker* ClassLinker::Create(const std::string& boot_class_path, InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700213 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800214 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700215 class_linker->Init(boot_class_path);
216 return class_linker.release();
217}
218
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800219ClassLinker* ClassLinker::Create(InternTable* intern_table) {
220 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700221 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700222 return class_linker.release();
223}
224
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800225ClassLinker::ClassLinker(InternTable* intern_table)
226 : dex_lock_("ClassLinker dex lock"),
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700227 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700228 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700229 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700230 init_done_(false),
231 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700232 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700233}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700234
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700235void CreateClassPath(const std::string& class_path,
236 std::vector<const DexFile*>& class_path_vector) {
237 std::vector<std::string> parsed;
238 Split(class_path, ':', parsed);
239 for (size_t i = 0; i < parsed.size(); ++i) {
240 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700241 if (dex_file == NULL) {
242 LOG(WARNING) << "Failed to open dex file " << parsed[i];
243 } else {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700244 class_path_vector.push_back(dex_file);
245 }
246 }
247}
248
249void ClassLinker::Init(const std::string& boot_class_path) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800250 VLOG(startup) << "ClassLinker::InitFrom entering boot_class_path=" << boot_class_path;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700251
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700252 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700253
Elliott Hughes30646832011-10-13 16:59:46 -0700254 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700255 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
256 CHECK(java_lang_Class.get() != NULL);
257 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700258 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700259 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700260
Elliott Hughes418d20f2011-09-22 14:00:39 -0700261 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700262 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
263 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700264
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700265 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700266 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
267 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700268 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700269 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700270 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700271
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700272 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700273 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
274 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700275
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700276 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700277 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700278
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700279 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700280 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
281 char_array_class->SetComponentType(char_class.get());
282 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700283
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700284 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700285 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
286 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700287 java_lang_String->SetObjectSize(sizeof(String));
288 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400289
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700290 // Create storage for root classes, save away our work so far (requires
291 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700292 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700293 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700294 SetClassRoot(kJavaLangClass, java_lang_Class.get());
295 SetClassRoot(kJavaLangObject, java_lang_Object.get());
296 SetClassRoot(kClassArrayClass, class_array_class.get());
297 SetClassRoot(kObjectArrayClass, object_array_class.get());
298 SetClassRoot(kCharArrayClass, char_array_class.get());
299 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700300
301 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700302 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
303 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
304 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
305 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
306 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
307 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
308 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
309 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700310
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700311 // Create array interface entries to populate once we can load system classes
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700312 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700313
314 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700315 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700316 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700317 IntArray::SetArrayClass(int_array_class.get());
318 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700319
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700320 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700321
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700322 // setup boot_class_path_ and register class_path now that we can
323 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700324 std::vector<const DexFile*> boot_class_path_vector;
325 CreateClassPath(boot_class_path, boot_class_path_vector);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700326 CHECK_NE(0U, boot_class_path_vector.size());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700327 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
328 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700329 CHECK(dex_file != NULL);
330 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700331 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700332
Elliott Hughes80609252011-09-23 17:24:51 -0700333 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700334 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700335 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700336 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700337 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700338 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
339
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700340 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
341 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700342 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700343 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700344 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700345 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700346
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700347 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700348 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700349 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700350 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700351 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700352 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700353
354 // now we can use FindSystemClass
355
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700356 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700357 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700358 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700359
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700360 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700361 java_lang_Object->SetStatus(Class::kStatusNotReady);
362 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700363 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700364 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
365 java_lang_String->SetStatus(Class::kStatusNotReady);
366 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700367 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700368 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
369
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700370 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700371 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
372 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
373
374 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
375 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
376
377 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700378 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700379
380 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
381 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
382
383 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700384 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700385
386 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
387 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
388
389 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
390 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
391
392 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
393 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
394
Elliott Hughes418d20f2011-09-22 14:00:39 -0700395 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700396 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700397
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700398 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700399 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700400
401 // Setup the single, global copies of "interfaces" and "iftable"
402 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
403 CHECK(java_lang_Cloneable != NULL);
404 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
405 CHECK(java_io_Serializable != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700406 // We assume that Cloneable/Serializable don't have superinterfaces --
407 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700408 // supers as well.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800409 array_iftable_->Set(0, AllocInterfaceEntry(java_lang_Cloneable));
410 array_iftable_->Set(1, AllocInterfaceEntry(java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700411
Elliott Hughes418d20f2011-09-22 14:00:39 -0700412 // Sanity check Class[] and Object[]'s interfaces
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800413 ClassHelper kh(class_array_class.get(), this);
414 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
415 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
416 kh.ChangeClass(object_array_class.get());
417 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
418 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
Elliott Hughes80609252011-09-23 17:24:51 -0700419 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700420 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700421 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700422 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700423
Elliott Hughes80609252011-09-23 17:24:51 -0700424 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
425 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700426 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700427
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700428 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700429 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700430 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700431
432 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700433 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700434 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700435
Ian Rogers466bb252011-10-14 03:29:56 -0700436 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
437
438 // Create java.lang.reflect.Proxy root
439 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
440 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
441
Brian Carlstrom1f870082011-08-23 16:02:11 -0700442 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700443 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
444 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700445 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700446 java_lang_ref_FinalizerReference->SetAccessFlags(
447 java_lang_ref_FinalizerReference->GetAccessFlags() |
448 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700449 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700450 java_lang_ref_PhantomReference->SetAccessFlags(
451 java_lang_ref_PhantomReference->GetAccessFlags() |
452 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700453 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700454 java_lang_ref_SoftReference->SetAccessFlags(
455 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700456 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700457 java_lang_ref_WeakReference->SetAccessFlags(
458 java_lang_ref_WeakReference->GetAccessFlags() |
459 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700460
Brian Carlstromaded5f72011-10-07 17:15:04 -0700461 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700462 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700463 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700464 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
465
466 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
467 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
468 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
469
470 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
471 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
472 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
473 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
474
Ian Rogers5167c972012-02-03 10:41:20 -0800475 // Set up java.lang.Throwable and java.lang.StackTraceElement as a convenience
476 SetClassRoot(kJavaLangThrowable, FindSystemClass("Ljava/lang/Throwable;"));
477 Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700478 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
479 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700480 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700481
Brian Carlstroma663ea52011-08-19 23:33:41 -0700482 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700483
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800484 VLOG(startup) << "ClassLinker::InitFrom exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700485}
486
487void ClassLinker::FinishInit() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800488 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700489
490 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700491 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700492 // as the types of the field can't be resolved prior to the runtime being
493 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700494 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700495 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700496 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
497
Elliott Hughesadb460d2011-10-05 17:02:34 -0700498 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
499
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800500 const DexFile& java_lang_dex = FindDexFile(java_lang_ref_Reference->GetDexCache());
501
Brian Carlstrom16192862011-09-12 17:50:06 -0700502 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800503 FieldHelper fh(pendingNext, this);
504 CHECK_STREQ(fh.GetName(), "pendingNext");
505 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
506 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700507
508 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800509 fh.ChangeField(queue);
510 CHECK_STREQ(fh.GetName(), "queue");
511 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
512 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700513
514 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800515 fh.ChangeField(queueNext);
516 CHECK_STREQ(fh.GetName(), "queueNext");
517 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
518 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700519
520 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800521 fh.ChangeField(referent);
522 CHECK_STREQ(fh.GetName(), "referent");
523 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
524 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700525
526 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800527 fh.ChangeField(zombie);
528 CHECK_STREQ(fh.GetName(), "zombie");
529 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
530 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700531
532 Heap::SetReferenceOffsets(referent->GetOffset(),
533 queue->GetOffset(),
534 queueNext->GetOffset(),
535 pendingNext->GetOffset(),
536 zombie->GetOffset());
537
Brian Carlstroma663ea52011-08-19 23:33:41 -0700538 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700539 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700540 ClassRoot class_root = static_cast<ClassRoot>(i);
541 Class* klass = GetClassRoot(class_root);
542 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700543 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700544 // note SetClassRoot does additional validation.
545 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700546 }
547
Elliott Hughes92f14b22011-10-06 12:29:54 -0700548 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700549
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700550 // disable the slow paths in FindClass and CreatePrimitiveClass now
551 // that Object, Class, and Object[] are setup
552 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700553
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800554 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700555}
556
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700557void ClassLinker::RunRootClinits() {
558 Thread* self = Thread::Current();
559 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
560 Class* c = GetClassRoot(ClassRoot(i));
561 if (!c->IsArrayClass() && !c->IsPrimitive()) {
562 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700563 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700564 }
565 }
566}
567
Brian Carlstromd601af82012-01-06 10:15:19 -0800568bool ClassLinker::GenerateOatFile(const std::string& dex_filename,
569 int oat_fd,
570 const std::string& oat_cache_filename) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800571 std::string dex2oat_string("/system/bin/dex2oat");
572#ifndef NDEBUG
573 dex2oat_string += 'd';
574#endif
575 const char* dex2oat = dex2oat_string.c_str();
576
577 const char* class_path = Runtime::Current()->GetClassPath().c_str();
578
579 std::string boot_image_option_string("--boot-image=");
Ian Rogers30fab402012-01-23 15:43:46 -0800580 boot_image_option_string += Heap::GetSpaces()[0]->AsImageSpace()->GetImageFilename();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800581 const char* boot_image_option = boot_image_option_string.c_str();
582
583 std::string dex_file_option_string("--dex-file=");
Brian Carlstromd601af82012-01-06 10:15:19 -0800584 dex_file_option_string += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800585 const char* dex_file_option = dex_file_option_string.c_str();
586
Brian Carlstromd601af82012-01-06 10:15:19 -0800587 std::string oat_fd_option_string("--oat-fd=");
Brian Carlstrom866c8622012-01-06 16:35:13 -0800588 StringAppendF(&oat_fd_option_string, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800589 const char* oat_fd_option = oat_fd_option_string.c_str();
590
591 std::string oat_name_option_string("--oat-name=");
592 oat_name_option_string += oat_cache_filename;
593 const char* oat_name_option = oat_name_option_string.c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800594
jeffhao262bf462011-10-20 18:36:32 -0700595 // fork and exec dex2oat
596 pid_t pid = fork();
597 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800598 // no allocation allowed between fork and exec
Ian Rogers725aee52012-01-11 11:56:56 -0800599
600 // change process groups, so we don't get reaped by ProcessManager
601 setpgid(0, 0);
602
jeffhao10037c82012-01-23 15:06:23 -0800603 VLOG(class_linker) << dex2oat
604 << " --runtime-arg -Xms64m"
605 << " --runtime-arg -Xmx64m"
606 << " --runtime-arg -classpath"
607 << " --runtime-arg " << class_path
608 << " " << boot_image_option
609 << " " << dex_file_option
610 << " " << oat_fd_option
611 << " " << oat_name_option;
612
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800613 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700614 "--runtime-arg", "-Xms64m",
615 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500616 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800617 "--runtime-arg", class_path,
618 boot_image_option,
619 dex_file_option,
Brian Carlstromd601af82012-01-06 10:15:19 -0800620 oat_fd_option,
621 oat_name_option,
jeffhao262bf462011-10-20 18:36:32 -0700622 NULL);
623
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800624 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
Brian Carlstromd601af82012-01-06 10:15:19 -0800625 return false;
jeffhao262bf462011-10-20 18:36:32 -0700626 } else {
627 // wait for dex2oat to finish
628 int status;
629 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
630 if (got_pid != pid) {
631 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
Brian Carlstromd601af82012-01-06 10:15:19 -0800632 return false;
jeffhao262bf462011-10-20 18:36:32 -0700633 }
634 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800635 LOG(ERROR) << dex2oat << " failed with dex-file=" << dex_filename;
636 return false;
jeffhao262bf462011-10-20 18:36:32 -0700637 }
638 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800639 return true;
jeffhao262bf462011-10-20 18:36:32 -0700640}
641
Brian Carlstrom866c8622012-01-06 16:35:13 -0800642void ClassLinker::RegisterOatFile(const OatFile& oat_file) {
643 MutexLock mu(dex_lock_);
644 RegisterOatFileLocked(oat_file);
645}
646
647void ClassLinker::RegisterOatFileLocked(const OatFile& oat_file) {
648 dex_lock_.AssertHeld();
649 oat_files_.push_back(&oat_file);
650}
651
Ian Rogers30fab402012-01-23 15:43:46 -0800652OatFile* ClassLinker::OpenOat(const ImageSpace* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700653 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700654 const Runtime* runtime = Runtime::Current();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700655 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800656 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
657 // check the down cast
658 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700659 std::string oat_filename;
660 oat_filename += runtime->GetHostPrefix();
661 oat_filename += oat_location->ToModifiedUtf8();
Ian Rogers30fab402012-01-23 15:43:46 -0800662 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBegin());
663 VLOG(startup) << "ClassLinker::OpenOat entering oat_filename=" << oat_filename;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700664 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700665 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700666 return NULL;
667 }
668 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
669 uint32_t image_oat_checksum = image_header.GetOatChecksum();
670 if (oat_checksum != image_oat_checksum) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800671 LOG(ERROR) << "Failed to match oat file checksum " << std::hex << oat_checksum
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700672 << " to expected oat checksum " << std::hex << oat_checksum
673 << " in image";
674 return NULL;
675 }
Brian Carlstrom866c8622012-01-06 16:35:13 -0800676 RegisterOatFileLocked(*oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800677 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700678 return oat_file;
679}
680
Brian Carlstromae826982011-11-09 01:33:42 -0800681const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800682 return FindOpenedOatFileFromDexLocation(dex_file.GetLocation(),
683 dex_file.GetLocationChecksum());
684}
685
686const OatFile* ClassLinker::FindOpenedOatFileFromDexLocation(const std::string& dex_location,
687 uint32_t dex_location_checksum) {
Brian Carlstromae826982011-11-09 01:33:42 -0800688 for (size_t i = 0; i < oat_files_.size(); i++) {
689 const OatFile* oat_file = oat_files_[i];
690 DCHECK(oat_file != NULL);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800691 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, false);
692 if (oat_dex_file != NULL
693 && oat_dex_file->GetDexFileLocationChecksum() == dex_location_checksum) {
Brian Carlstromae826982011-11-09 01:33:42 -0800694 return oat_file;
695 }
696 }
697 return NULL;
698}
699
Brian Carlstromd601af82012-01-06 10:15:19 -0800700class LockedFd {
701 public:
702 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
703 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
704 if (fd == -1) {
705 PLOG(ERROR) << "Failed to open file '" << name << "'";
706 return NULL;
707 }
708 fchmod(fd, mode);
709
710 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
711 // try to lock non-blocking so we can log if we need may need to block
712 int result = flock(fd, LOCK_EX | LOCK_NB);
713 if (result == -1) {
714 LOG(WARNING) << "sleeping while locking file " << name;
715 // retry blocking
716 result = flock(fd, LOCK_EX);
717 }
718 if (result == -1) {
719 PLOG(ERROR) << "Failed to lock file '" << name << "'";
720 close(fd);
721 return NULL;
722 }
723 return new LockedFd(fd);
724 }
725
726 int GetFd() const {
727 return fd_;
728 }
729
730 ~LockedFd() {
731 if (fd_ != -1) {
732 int result = flock(fd_, LOCK_UN);
733 if (result == -1) {
734 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
735 }
736 close(fd_);
737 }
738 }
739
740 private:
741 explicit LockedFd(int fd) : fd_(fd) {}
742
743 int fd_;
744};
745
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800746static const DexFile* FindDexFileInOatLocation(const std::string& dex_location,
747 uint32_t dex_location_checksum,
748 const std::string& oat_location) {
749 UniquePtr<OatFile> oat_file(OatFile::Open(oat_location, "", NULL));
750 if (oat_file.get() == NULL) {
751 return NULL;
752 }
753 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
754 if (oat_dex_file == NULL) {
755 return NULL;
756 }
757 if (oat_dex_file->GetDexFileLocationChecksum() != dex_location_checksum) {
758 return NULL;
759 }
760 Runtime::Current()->GetClassLinker()->RegisterOatFile(*oat_file.release());
761 return oat_dex_file->OpenDexFile();
762}
763
764const DexFile* ClassLinker::FindOrCreateOatFileForDexLocation(const std::string& dex_location,
765 const std::string& oat_location) {
766 uint32_t dex_location_checksum;
767 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) {
768 LOG(ERROR) << "Failed to compute checksum '" << dex_location << "'";
769 return NULL;
770 }
771
772 // Check if we already have an up-to-date output file
773 const DexFile* dex_file = FindDexFileInOatLocation(dex_location,
774 dex_location_checksum,
775 oat_location);
776 if (dex_file != NULL) {
777 return dex_file;
778 }
779
780 // Generate the output oat file for the dex file
781 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
782 UniquePtr<File> file(OS::OpenFile(oat_location.c_str(), true));
783 if (file.get() == NULL) {
784 LOG(ERROR) << "Failed to create oat file: " << oat_location;
785 return NULL;
786 }
787 if (!class_linker->GenerateOatFile(dex_location, file->Fd(), oat_location)) {
788 LOG(ERROR) << "Failed to generate oat file: " << oat_location;
789 return NULL;
790 }
791 // Open the oat from file descriptor we passed to GenerateOatFile
792 if (lseek(file->Fd(), 0, SEEK_SET) != 0) {
793 LOG(ERROR) << "Failed to seek to start of generated oat file: " << oat_location;
794 return NULL;
795 }
796 const OatFile* oat_file = OatFile::Open(*file.get(), oat_location, NULL);
797 if (oat_file == NULL) {
798 LOG(ERROR) << "Failed to open generated oat file: " << oat_location;
799 return NULL;
800 }
801 class_linker->RegisterOatFile(*oat_file);
802 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
803 if (oat_dex_file == NULL) {
804 LOG(ERROR) << "Failed to find dex file in generated oat file: " << oat_location;
805 return NULL;
806 }
807 return oat_dex_file->OpenDexFile();
808}
809
810const DexFile* ClassLinker::FindDexFileInOatFileFromDexLocation(const std::string& dex_location) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700811 MutexLock mu(dex_lock_);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800812
813 uint32_t dex_location_checksum;
814 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) {
815 LOG(WARNING) << "Failed to compute checksum: " << dex_location;
816 return NULL;
817 }
818
819 const OatFile* open_oat_file = FindOpenedOatFileFromDexLocation(dex_location, dex_location_checksum);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800820 if (open_oat_file != NULL) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800821 return open_oat_file->GetOatDexFile(dex_location)->OpenDexFile();
Brian Carlstromae826982011-11-09 01:33:42 -0800822 }
823
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800824 // Look for an existing file first next to dex and in art-cache
825 std::string oat_filename(OatFile::DexFilenameToOatFilename(dex_location));
826 const OatFile* oat_file(FindOatFileFromOatLocation(oat_filename));
827 if (oat_file != NULL) {
828 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
829 if (dex_location_checksum == oat_dex_file->GetDexFileLocationChecksum()) {
830 return oat_file->GetOatDexFile(dex_location)->OpenDexFile();
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700831 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800832 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
833 << " checksum ( " << std::hex << oat_dex_file->GetDexFileLocationChecksum()
834 << ") mismatch with " << dex_location
835 << " (" << std::hex << dex_location_checksum << ")--- regenerating";
836 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
837 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
Brian Carlstromd601af82012-01-06 10:15:19 -0800838 }
jeffhao262bf462011-10-20 18:36:32 -0700839 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800840 // Try to generate oat file if it wasn't found or was obsolete.
841 std::string oat_cache_filename(GetArtCacheFilenameOrDie(oat_filename));
842 return FindOrCreateOatFileForDexLocation(dex_location, oat_cache_filename);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700843}
844
Brian Carlstromae826982011-11-09 01:33:42 -0800845const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700846 for (size_t i = 0; i < oat_files_.size(); i++) {
847 const OatFile* oat_file = oat_files_[i];
848 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800849 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700850 return oat_file;
851 }
852 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700853 return NULL;
854}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700855
Brian Carlstromae826982011-11-09 01:33:42 -0800856const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
jeffhaof6174e82012-01-31 16:14:17 -0800857 MutexLock mu(dex_lock_);
858 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
859 if (oat_file != NULL) {
860 return oat_file;
861 }
862
863 oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700864 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800865 if (oat_location.empty() || oat_location[0] != '/') {
866 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700867 return NULL;
868 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700869
Brian Carlstroma9f19782011-10-13 00:14:47 -0700870 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Elliott Hughes95572412011-12-13 18:14:20 -0800871 std::string cache_location(GetArtCacheFilenameOrDie(oat_location));
Brian Carlstromae826982011-11-09 01:33:42 -0800872 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700873 if (oat_file != NULL) {
874 return oat_file;
875 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700876 oat_file = OatFile::Open(cache_location, "", NULL);
877 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800878 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700879 return NULL;
880 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700881 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700882
Brian Carlstromae826982011-11-09 01:33:42 -0800883 CHECK(oat_file != NULL) << oat_location;
jeffhaof6174e82012-01-31 16:14:17 -0800884 RegisterOatFileLocked(*oat_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700885 return oat_file;
886}
887
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700888void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800889 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700890 CHECK(!init_done_);
891
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700892 const std::vector<Space*>& spaces = Heap::GetSpaces();
893 for (size_t i = 0; i < spaces.size(); i++) {
Ian Rogers30fab402012-01-23 15:43:46 -0800894 if (spaces[i]->IsImageSpace()) {
895 ImageSpace* space = spaces[i]->AsImageSpace();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700896 OatFile* oat_file = OpenOat(space);
897 CHECK(oat_file != NULL) << "Failed to open oat file for image";
898 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
899 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
900
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800901 if (i == 0) {
902 // Special case of setting up the String class early so that we can test arbitrary objects
903 // as being Strings or not
Ian Rogers30fab402012-01-23 15:43:46 -0800904 Class* java_lang_String = space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800905 ->AsObjectArray<Class>()->Get(kJavaLangString);
906 String::SetClass(java_lang_String);
907 }
908
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700909 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
910 static_cast<uint32_t>(dex_caches->GetLength()));
911 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700912 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800913 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom89521892011-12-07 22:05:07 -0800914 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
915 const DexFile* dex_file = oat_dex_file->OpenDexFile();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700916 if (dex_file == NULL) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800917 LOG(FATAL) << "Failed to open dex file " << dex_file_location
918 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700919 }
920
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800921 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700922
Brian Carlstromdf143242011-10-10 18:05:34 -0700923 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700924 }
925 }
926 }
927
Brian Carlstroma663ea52011-08-19 23:33:41 -0700928 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
929 DCHECK(heap_bitmap != NULL);
930
Brian Carlstroma663ea52011-08-19 23:33:41 -0700931 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700932 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700933
934 // reinit class_roots_
Ian Rogers30fab402012-01-23 15:43:46 -0800935 Object* class_roots_object =
936 spaces[0]->AsImageSpace()->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700937 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700938
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800939 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700940 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
941 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800942 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700943 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700944 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700945 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
946 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
947 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
948 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
949 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
950 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
951 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
952 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700953 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Ian Rogers5167c972012-02-03 10:41:20 -0800954 Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700955 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700956
957 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700958
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800959 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700960}
961
Brian Carlstrom78128a62011-09-15 17:21:19 -0700962void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700963 DCHECK(obj != NULL);
964 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700965 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700966
Elliott Hughesdbb40792011-11-18 17:05:22 -0800967 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700968 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700969 return;
970 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700971 if (obj->IsClass()) {
972 // restore class to ClassLinker::classes_ table
973 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800974 ClassHelper kh(klass, class_linker);
Brian Carlstrom07bb8552012-01-18 22:10:50 -0800975 Class* existing = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
976 DCHECK(existing == NULL) << kh.GetDescriptor();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700977 return;
978 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700979}
980
981// Keep in sync with InitCallback. Anything we visit, we need to
982// reinit references to when reinitializing a ClassLinker from a
983// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700984void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
985 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700986
987 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700988 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700989 }
990
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700991 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700992 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700993 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700994 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700995 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700996 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700997 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700998 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700999
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001000 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001001}
1002
Elliott Hughesa2155262011-11-16 16:26:58 -08001003void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
1004 MutexLock mu(classes_lock_);
1005 typedef Table::const_iterator It; // TODO: C++0x auto
1006 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
1007 if (!visitor(it->second, arg)) {
1008 return;
1009 }
1010 }
1011 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
1012 if (!visitor(it->second, arg)) {
1013 return;
1014 }
1015 }
1016}
1017
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001018ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001019 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001020 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -07001021 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001022 BooleanArray::ResetArrayClass();
1023 ByteArray::ResetArrayClass();
1024 CharArray::ResetArrayClass();
1025 DoubleArray::ResetArrayClass();
1026 FloatArray::ResetArrayClass();
1027 IntArray::ResetArrayClass();
1028 LongArray::ResetArrayClass();
1029 ShortArray::ResetArrayClass();
1030 PathClassLoader::ResetClass();
Ian Rogers5167c972012-02-03 10:41:20 -08001031 Throwable::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001032 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001033 STLDeleteElements(&boot_class_path_);
1034 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001035}
1036
1037DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001038 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
1039 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001040 return NULL;
1041 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001042 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
1043 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001044 return NULL;
1045 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001046 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
1047 if (strings.get() == NULL) {
1048 return NULL;
1049 }
1050 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
1051 if (types.get() == NULL) {
1052 return NULL;
1053 }
1054 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
1055 if (methods.get() == NULL) {
1056 return NULL;
1057 }
1058 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
1059 if (fields.get() == NULL) {
1060 return NULL;
1061 }
1062 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
1063 if (code_and_direct_methods.get() == NULL) {
1064 return NULL;
1065 }
1066 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
1067 if (initialized_static_storage.get() == NULL) {
1068 return NULL;
1069 }
1070
1071 dex_cache->Init(location.get(),
1072 strings.get(),
1073 types.get(),
1074 methods.get(),
1075 fields.get(),
1076 code_and_direct_methods.get(),
1077 initialized_static_storage.get());
1078 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001079}
1080
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001081CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
1082 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -07001083}
1084
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001085InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
1086 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001087 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
1088 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001089 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001090 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001091}
1092
Brian Carlstrom4873d462011-08-21 15:23:39 -07001093Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
1094 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001095 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001096 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001097 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001098 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001099}
1100
Brian Carlstrom4873d462011-08-21 15:23:39 -07001101Class* ClassLinker::AllocClass(size_t class_size) {
1102 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001103}
1104
Jesse Wilson35baaab2011-08-10 16:18:03 -04001105Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001106 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -07001107}
1108
1109Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001110 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001111}
1112
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001113ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
1114 return ObjectArray<StackTraceElement>::Alloc(
1115 GetClassRoot(kJavaLangStackTraceElementArrayClass),
1116 length);
1117}
1118
Brian Carlstromaded5f72011-10-07 17:15:04 -07001119Class* EnsureResolved(Class* klass) {
1120 DCHECK(klass != NULL);
1121 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -07001122 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001123 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001124 ObjectLock lock(klass);
1125 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001126 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001127 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001128 PrettyDescriptor(klass).c_str());
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001129 klass->SetStatus(Class::kStatusError);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001130 return NULL;
1131 }
1132 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001133 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001134 lock.Wait();
1135 }
1136 }
1137 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001138 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001139 return NULL;
1140 }
1141 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001142 CHECK(klass->IsResolved()) << PrettyClass(klass);
1143 CHECK(!self->IsExceptionPending())
1144 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
1145 return klass;
1146}
1147
Elliott Hughesdb7d5e92011-12-16 18:47:37 -08001148Class* ClassLinker::FindSystemClass(const char* descriptor) {
1149 return FindClass(descriptor, NULL);
1150}
1151
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001152Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001153 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001154 Thread* self = Thread::Current();
1155 DCHECK(self != NULL);
1156 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001157 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001158 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1159 // for primitive classes that aren't backed by dex files.
1160 return FindPrimitiveClass(descriptor[0]);
1161 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001162 // Find the class in the loaded classes table.
1163 Class* klass = LookupClass(descriptor, class_loader);
1164 if (klass != NULL) {
1165 return EnsureResolved(klass);
1166 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001167 // Class is not yet loaded.
1168 if (descriptor[0] == '[') {
1169 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001170
Jesse Wilson47daf872011-11-23 11:42:45 -05001171 } else if (class_loader == NULL) {
1172 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1173 if (pair.second != NULL) {
1174 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1175 }
1176
1177 } else if (ClassLoader::UseCompileTimeClassPath()) {
1178 // first try the boot class path
1179 Class* system_class = FindSystemClass(descriptor);
1180 if (system_class != NULL) {
1181 return system_class;
1182 }
1183 CHECK(self->IsExceptionPending());
1184 self->ClearException();
1185
1186 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001187 const std::vector<const DexFile*>& class_path
1188 = ClassLoader::GetCompileTimeClassPath(class_loader);
1189 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001190 if (pair.second != NULL) {
1191 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001192 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001193
1194 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001195 std::string class_name_string(DescriptorToDot(descriptor));
Elliott Hughes09d4d012012-02-03 17:44:20 -08001196 ScopedThreadStateChange tsc(self, Thread::kNative);
Elliott Hughes748382f2012-01-26 18:07:38 -08001197 JNIEnv* env = self->GetJniEnv();
Jesse Wilson47daf872011-11-23 11:42:45 -05001198 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1199 CHECK(c.get() != NULL);
1200 // TODO: cache method?
1201 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1202 CHECK(mid != NULL);
1203 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1204 if (class_name_object.get() == NULL) {
1205 return NULL;
1206 }
1207 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
Ian Rogers761bfa82012-01-11 10:14:05 -08001208 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid,
1209 class_name_object.get()));
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001210 if (env->ExceptionCheck()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001211 // If the ClassLoader threw, pass that exception up.
1212 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001213 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001214 // broken loader - throw NPE to be compatible with Dalvik
1215 ThrowNullPointerException("ClassLoader.loadClass returned null for %s",
1216 class_name_string.c_str());
1217 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001218 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08001219 // success, return Class*
Ian Rogers6b0870d2011-12-15 19:38:12 -08001220 return Decode<Class*>(env, result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001221 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001222 }
1223
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001224 ThrowNoClassDefFoundError("Class %s not found", PrintableString(StringPiece(descriptor)).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001225 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001226}
1227
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001228Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001229 const ClassLoader* class_loader,
1230 const DexFile& dex_file,
1231 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001232 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001233 // Load the class from the dex file.
1234 if (!init_done_) {
1235 // finish up init of hand crafted class_roots_
1236 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001237 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001238 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001239 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001240 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001241 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001242 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001243 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001244 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001245 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001246 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001247 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001248 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001249 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001250 }
1251 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001252 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001253 }
1254 klass->SetDexCache(FindDexCache(dex_file));
1255 LoadClass(dex_file, dex_class_def, klass, class_loader);
1256 // Check for a pending exception during load
1257 Thread* self = Thread::Current();
1258 if (self->IsExceptionPending()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001259 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001260 return NULL;
1261 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001262 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001263 klass->SetClinitThreadId(self->GetTid());
1264 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001265 Class* existing = InsertClass(descriptor, klass.get(), false);
1266 if (existing != NULL) {
1267 // We failed to insert because we raced with another thread.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001268 klass->SetClinitThreadId(0);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001269 klass.reset(existing);
1270 return EnsureResolved(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001271 }
1272 // Finish loading (if necessary) by finding parents
1273 CHECK(!klass->IsLoaded());
1274 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1275 // Loading failed.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001276 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001277 lock.NotifyAll();
1278 return NULL;
1279 }
1280 CHECK(klass->IsLoaded());
1281 // Link the class (if necessary)
1282 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001283 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001284 // Linking failed.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001285 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001286 lock.NotifyAll();
1287 return NULL;
1288 }
1289 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001290
1291 /*
1292 * We send CLASS_PREPARE events to the debugger from here. The
1293 * definition of "preparation" is creating the static fields for a
1294 * class and initializing them to the standard default values, but not
1295 * executing any code (that comes later, during "initialization").
1296 *
1297 * We did the static preparation in LinkClass.
1298 *
1299 * The class has been prepared and resolved but possibly not yet verified
1300 * at this point.
1301 */
1302 Dbg::PostClassPrepare(klass.get());
1303
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001304 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001305}
1306
Brian Carlstrom4873d462011-08-21 15:23:39 -07001307// Precomputes size that will be needed for Class, matching LinkStaticFields
1308size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1309 const DexFile::ClassDef& dex_class_def) {
1310 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001311 size_t num_ref = 0;
1312 size_t num_32 = 0;
1313 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001314 if (class_data != NULL) {
1315 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1316 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001317 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001318 char c = descriptor[0];
1319 if (c == 'L' || c == '[') {
1320 num_ref++;
1321 } else if (c == 'J' || c == 'D') {
1322 num_64++;
1323 } else {
1324 num_32++;
1325 }
1326 }
1327 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001328 // start with generic class data
1329 size_t size = sizeof(Class);
1330 // follow with reference fields which must be contiguous at start
1331 size += (num_ref * sizeof(uint32_t));
1332 // if there are 64-bit fields to add, make sure they are aligned
1333 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1334 if (num_32 != 0) {
1335 // use an available 32-bit field for padding
1336 num_32--;
1337 }
1338 size += sizeof(uint32_t); // either way, we are adding a word
1339 DCHECK_EQ(size, RoundUp(size, 8));
1340 }
1341 // tack on any 64-bit fields now that alignment is assured
1342 size += (num_64 * sizeof(uint64_t));
1343 // tack on any remaining 32-bit fields
1344 size += (num_32 * sizeof(uint32_t));
1345 return size;
1346}
1347
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001348void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001349 // Every kind of method should at least get an invoke stub from the oat_method.
1350 // non-abstract methods also get their code pointers.
1351 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001352 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001353
1354 if (method->IsAbstract()) {
1355 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1356 return;
1357 }
1358 if (method->IsNative()) {
1359 // unregistering restores the dlsym lookup stub
1360 method->UnregisterNative();
jeffhao26c0a1a2012-01-17 16:28:33 -08001361 }
1362
1363 if (Runtime::Current()->IsMethodTracingActive()) {
1364#if defined(__arm__)
1365 Trace* tracer = Runtime::Current()->GetTracer();
1366 void* trace_stub = reinterpret_cast<void*>(art_trace_entry_from_code);
1367 tracer->SaveAndUpdateCode(method.get(), trace_stub);
1368#else
1369 UNIMPLEMENTED(WARNING);
1370#endif
Brian Carlstrom92827a52011-10-10 15:50:01 -07001371 }
1372}
1373
Brian Carlstromf615a612011-07-23 12:50:34 -07001374void ClassLinker::LoadClass(const DexFile& dex_file,
1375 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001376 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001377 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001378 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001379 CHECK(klass->GetDexCache() != NULL);
1380 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001381 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001382 CHECK(descriptor != NULL);
1383
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001384 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001385 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001386 // Make sure that none of our runtime-only flags are set.
1387 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001388 klass->SetAccessFlags(access_flags);
1389 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001390 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001391 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001392
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001393 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001394
Ian Rogers0571d352011-11-03 19:51:38 -07001395 // Load fields fields.
1396 const byte* class_data = dex_file.GetClassData(dex_class_def);
1397 if (class_data == NULL) {
1398 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001399 }
Ian Rogers0571d352011-11-03 19:51:38 -07001400 ClassDataItemIterator it(dex_file, class_data);
1401 if (it.NumStaticFields() != 0) {
1402 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1403 }
1404 if (it.NumInstanceFields() != 0) {
1405 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1406 }
1407 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1408 SirtRef<Field> sfield(AllocField());
1409 klass->SetStaticField(i, sfield.get());
1410 LoadField(dex_file, it, klass, sfield);
1411 }
1412 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1413 SirtRef<Field> ifield(AllocField());
1414 klass->SetInstanceField(i, ifield.get());
1415 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001416 }
1417
Brian Carlstromaded5f72011-10-07 17:15:04 -07001418 UniquePtr<const OatFile::OatClass> oat_class;
1419 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001420 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
1421 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << descriptor;
1422 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1423 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << descriptor;
1424 uint32_t class_def_index;
1425 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1426 CHECK(found) << dex_file.GetLocation() << " " << descriptor;
1427 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
1428 CHECK(oat_class.get() != NULL) << dex_file.GetLocation() << " " << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001429 }
Ian Rogers0571d352011-11-03 19:51:38 -07001430 // Load methods.
1431 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001432 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001433 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001434 }
Ian Rogers0571d352011-11-03 19:51:38 -07001435 if (it.NumVirtualMethods() != 0) {
1436 // TODO: append direct methods to class object
1437 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001438 }
Ian Rogers0571d352011-11-03 19:51:38 -07001439 size_t method_index = 0;
1440 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1441 SirtRef<Method> method(AllocMethod());
1442 klass->SetDirectMethod(i, method.get());
1443 LoadMethod(dex_file, it, klass, method);
1444 if (oat_class.get() != NULL) {
1445 LinkCode(method, oat_class.get(), method_index);
1446 }
1447 method_index++;
1448 }
1449 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1450 SirtRef<Method> method(AllocMethod());
1451 klass->SetVirtualMethod(i, method.get());
1452 LoadMethod(dex_file, it, klass, method);
1453 if (oat_class.get() != NULL) {
1454 LinkCode(method, oat_class.get(), method_index);
1455 }
1456 method_index++;
1457 }
1458 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001459}
1460
Ian Rogers0571d352011-11-03 19:51:38 -07001461void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1462 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001463 uint32_t field_idx = it.GetMemberIndex();
1464 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001465 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001466 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001467}
1468
Ian Rogers0571d352011-11-03 19:51:38 -07001469void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1470 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001471 uint32_t method_idx = it.GetMemberIndex();
1472 dst->SetDexMethodIndex(method_idx);
1473 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001474 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001475
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001476
1477 StringPiece method_name(dex_file.GetMethodName(method_id));
1478 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001479 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1480 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001481
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001482 if (method_name == "finalize") {
1483 // Create the prototype for a signature of "()V"
1484 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1485 if (void_string_id != NULL) {
1486 const DexFile::TypeId* void_type_id =
1487 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1488 if (void_type_id != NULL) {
1489 std::vector<uint16_t> no_args;
1490 const DexFile::ProtoId* finalizer_proto =
1491 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1492 if (finalizer_proto != NULL) {
1493 // We have the prototype in the dex file
1494 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1495 klass->SetFinalizable();
1496 } else {
1497 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1498 // The Enum class declares a "final" finalize() method to prevent subclasses from
1499 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1500 // subclasses, so we exclude it here.
1501 // We also want to avoid setting the flag on Object, where we know that finalize() is
1502 // empty.
1503 if (klass_descriptor != "Ljava/lang/Object;" &&
1504 klass_descriptor != "Ljava/lang/Enum;") {
1505 klass->SetFinalizable();
1506 }
1507 }
1508 }
1509 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001510 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001511 }
Ian Rogers0571d352011-11-03 19:51:38 -07001512 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001513 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001514
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001515 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1516 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1517 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1518 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1519 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1520 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001521}
1522
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001523void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001524 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1525 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001526}
1527
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001528void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1529 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001530 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001531 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001532}
1533
Brian Carlstromaded5f72011-10-07 17:15:04 -07001534bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001535 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001536 for (size_t i = 0; i != dex_files_.size(); ++i) {
1537 if (dex_files_[i] == &dex_file) {
1538 return true;
1539 }
1540 }
1541 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001542}
1543
Brian Carlstromaded5f72011-10-07 17:15:04 -07001544bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001545 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001546 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001547}
1548
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001549void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001550 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001551 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001552 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001553 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001554 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001555}
1556
Brian Carlstromaded5f72011-10-07 17:15:04 -07001557void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001558 {
1559 MutexLock mu(dex_lock_);
1560 if (IsDexFileRegisteredLocked(dex_file)) {
1561 return;
1562 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001563 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001564 // Don't alloc while holding the lock, since allocation may need to
1565 // suspend all threads and another thread may need the dex_lock_ to
1566 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001567 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001568 {
1569 MutexLock mu(dex_lock_);
1570 if (IsDexFileRegisteredLocked(dex_file)) {
1571 return;
1572 }
1573 RegisterDexFileLocked(dex_file, dex_cache);
1574 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001575}
1576
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001577void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001578 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001579 RegisterDexFileLocked(dex_file, dex_cache);
1580}
1581
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001582const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001583 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001584 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001585 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1586 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001587 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001588 }
1589 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001590 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001591 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001592}
1593
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001594DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001595 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001596 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001597 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001598 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001599 }
1600 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001601 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001602 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001603}
1604
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001605Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1606 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001607 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001608 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001609 CHECK(primitive_class != NULL);
1610 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001611 primitive_class->SetPrimitiveType(type);
1612 primitive_class->SetStatus(Class::kStatusInitialized);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001613 Class* existing = InsertClass(descriptor, primitive_class, false);
1614 CHECK(existing == NULL) << "InitPrimitiveClass(" << descriptor << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001615 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001616}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001617
Brian Carlstrombe977852011-07-19 14:54:54 -07001618// Create an array class (i.e. the class object for the array, not the
1619// array itself). "descriptor" looks like "[C" or "[[[[B" or
1620// "[Ljava/lang/String;".
1621//
1622// If "descriptor" refers to an array of primitives, look up the
1623// primitive type's internally-generated class object.
1624//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001625// "class_loader" is the class loader of the class that's referring to
1626// us. It's used to ensure that we're looking for the element type in
1627// the right context. It does NOT become the class loader for the
1628// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001629//
1630// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001631Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001632 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001633
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001634 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001635 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001636 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001637 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001638 return NULL;
1639 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001640
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001641 // See if the component type is already loaded. Array classes are
1642 // always associated with the class loader of their underlying
1643 // element type -- an array of Strings goes with the loader for
1644 // java/lang/String -- so we need to look for it there. (The
1645 // caller should have checked for the existence of the class
1646 // before calling here, but they did so with *their* class loader,
1647 // not the component type's loader.)
1648 //
1649 // If we find it, the caller adds "loader" to the class' initiating
1650 // loader list, which should prevent us from going through this again.
1651 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001652 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001653 // are the same, because our caller (FindClass) just did the
1654 // lookup. (Even if we get this wrong we still have correct behavior,
1655 // because we effectively do this lookup again when we add the new
1656 // class to the hash table --- necessary because of possible races with
1657 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001658 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001659 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001660 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001661 return new_class;
1662 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001663 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001664
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001665 // Fill out the fields in the Class.
1666 //
1667 // It is possible to execute some methods against arrays, because
1668 // all arrays are subclasses of java_lang_Object_, so we need to set
1669 // up a vtable. We can just point at the one in java_lang_Object_.
1670 //
1671 // Array classes are simple enough that we don't need to do a full
1672 // link step.
1673
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001674 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001675 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001676 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001677 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001678 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001679 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001680 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001681 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001682 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001683 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001684 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001685 }
1686 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001687 if (new_class.get() == NULL) {
1688 new_class.reset(AllocClass(sizeof(Class)));
1689 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001690 return NULL;
1691 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001692 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001693 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001694 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001695 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001696 new_class->SetSuperClass(java_lang_Object);
1697 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001698 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001699 new_class->SetClassLoader(component_type->GetClassLoader());
1700 new_class->SetStatus(Class::kStatusInitialized);
1701 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001702 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001703
1704
1705 // All arrays have java/lang/Cloneable and java/io/Serializable as
1706 // interfaces. We need to set that up here, so that stuff like
1707 // "instanceof" works right.
1708 //
1709 // Note: The GC could run during the call to FindSystemClass,
1710 // so we need to make sure the class object is GC-valid while we're in
1711 // there. Do this by clearing the interface list so the GC will just
1712 // think that the entries are null.
1713
1714
1715 // Use the single, global copies of "interfaces" and "iftable"
1716 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001717 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001718 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001719
1720 // Inherit access flags from the component type. Arrays can't be
1721 // used as a superclass or interface, so we want to add "final"
1722 // and remove "interface".
1723 //
1724 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001725 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001726 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001727 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1728 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001729
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001730 Class* existing = InsertClass(descriptor, new_class.get(), false);
1731 if (existing == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001732 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001733 }
1734 // Another thread must have loaded the class after we
1735 // started but before we finished. Abandon what we've
1736 // done.
1737 //
1738 // (Yes, this happens.)
1739
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001740 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001741}
1742
1743Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001744 switch (Primitive::GetType(type)) {
1745 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001746 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001747 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001748 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001749 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001750 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001751 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001752 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001753 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001754 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001755 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001756 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001757 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001758 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001759 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001760 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001761 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001762 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001763 case Primitive::kPrimNot:
1764 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001765 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001766 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001767 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001768 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001769}
1770
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001771Class* ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001772 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001773 DexCache* dex_cache = klass->GetDexCache();
1774 std::string source;
1775 if (dex_cache != NULL) {
1776 source += " from ";
1777 source += dex_cache->GetLocation()->ToModifiedUtf8();
1778 }
1779 LOG(INFO) << "Loaded class " << descriptor << source;
1780 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001781 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001782 MutexLock mu(classes_lock_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001783 Table& classes = image_class ? image_classes_ : classes_;
1784 Class* existing = LookupClass(descriptor.data(), klass->GetClassLoader(), hash, classes);
1785#ifndef NDEBUG
1786 // Check we don't have the class in the other table in error
1787 Table& other_classes = image_class ? classes_ : image_classes_;
1788 CHECK(LookupClass(descriptor.data(), klass->GetClassLoader(), hash, other_classes) == NULL);
1789#endif
1790 if (existing != NULL) {
1791 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07001792 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001793 classes.insert(std::make_pair(hash, klass));
1794 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001795}
1796
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001797bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1798 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001799 MutexLock mu(classes_lock_);
Elliott Hughese5448b52012-01-18 16:44:06 -08001800 typedef Table::iterator It; // TODO: C++0x auto
Brian Carlstromae826982011-11-09 01:33:42 -08001801 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001802 ClassHelper kh;
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001803 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001804 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001805 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001806 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001807 classes_.erase(it);
1808 return true;
1809 }
1810 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001811 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001812 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001813 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001814 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001815 image_classes_.erase(it);
1816 return true;
1817 }
1818 }
1819 return false;
1820}
1821
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001822Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1823 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001824 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001825 // TODO: determine if its better to search classes_ or image_classes_ first
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001826 Class* klass = LookupClass(descriptor, class_loader, hash, classes_);
1827 if (klass != NULL) {
1828 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001829 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001830 return LookupClass(descriptor, class_loader, hash, image_classes_);
1831}
1832
1833Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader,
1834 size_t hash, const Table& classes) {
1835 ClassHelper kh(NULL, this);
1836 typedef Table::const_iterator It; // TODO: C++0x auto
1837 for (It it = classes.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001838 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001839 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001840 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001841#ifndef NDEBUG
1842 for (++it; it != end && it->first == hash; ++it) {
Ian Rogersd85016c2012-02-03 18:27:34 -08001843 Class* klass2 = it->second;
1844 kh.ChangeClass(klass2);
1845 CHECK(!(strcmp(descriptor, kh.GetDescriptor()) == 0 && klass2->GetClassLoader() == class_loader))
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001846 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
Ian Rogersd85016c2012-02-03 18:27:34 -08001847 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001848 }
1849#endif
Ian Rogers5d76c432011-10-31 21:42:49 -07001850 return klass;
1851 }
1852 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001853 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001854}
1855
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001856void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001857 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001858 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001859 MutexLock mu(classes_lock_);
1860 typedef Table::const_iterator It; // TODO: C++0x auto
1861 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001862 ClassHelper kh(NULL, this);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001863 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001864 Class* klass = it->second;
1865 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001866 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001867 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001868 }
1869 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001870 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001871 Class* klass = it->second;
1872 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001873 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001874 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001875 }
1876 }
1877}
1878
Ian Rogersc20a83e2012-01-18 18:15:32 -08001879#ifndef NDEBUG
1880static void CheckMethodsHaveGcMaps(Class* klass) {
1881 if (!Runtime::Current()->IsStarted()) {
1882 return;
1883 }
1884 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
1885 Method* method = klass->GetDirectMethod(i);
1886 if (!method->IsNative() && !method->IsAbstract()) {
1887 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1888 }
1889 }
1890 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
1891 Method* method = klass->GetVirtualMethod(i);
1892 if (!method->IsNative() && !method->IsAbstract()) {
1893 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1894 }
1895 }
1896}
1897#else
1898static void CheckMethodsHaveGcMaps(Class* klass) {
1899}
1900#endif
1901
jeffhao98eacac2011-09-14 16:11:53 -07001902void ClassLinker::VerifyClass(Class* klass) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001903 ObjectLock lock(klass);
1904
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001905 // TODO: assert that the monitor on the Class is held
jeffhao98eacac2011-09-14 16:11:53 -07001906 if (klass->IsVerified()) {
1907 return;
1908 }
1909
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001910 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved) << PrettyClass(klass);
jeffhao98eacac2011-09-14 16:11:53 -07001911 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001912
Ian Rogers1c5eb702012-02-01 09:18:34 -08001913 // Verify super class
1914 Class* super = klass->GetSuperClass();
1915 std::string error_msg;
1916 if (super != NULL) {
1917 // Acquire lock to prevent races on verifying the super class
1918 ObjectLock lock(super);
1919
1920 if (!super->IsVerified() && !super->IsErroneous()) {
1921 Runtime::Current()->GetClassLinker()->VerifyClass(super);
1922 }
1923 if (!super->IsVerified()) {
1924 error_msg = "Rejecting class ";
1925 error_msg += PrettyDescriptor(klass);
1926 error_msg += " that attempts to sub-class erroneous class ";
1927 error_msg += PrettyDescriptor(super);
1928 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
1929 Thread* self = Thread::Current();
1930 SirtRef<Throwable> cause(self->GetException());
1931 if (cause.get() != NULL) {
1932 self->ClearException();
1933 }
1934 self->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
1935 if (cause.get() != NULL) {
1936 self->GetException()->SetCause(cause.get());
1937 }
1938 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyDescriptor(klass);
1939 klass->SetStatus(Class::kStatusError);
1940 return;
1941 }
1942 }
1943
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001944 // Try to use verification information from oat file, otherwise do runtime verification
1945 const DexFile& dex_file = FindDexFile(klass->GetDexCache());
Ian Rogers1c5eb702012-02-01 09:18:34 -08001946 if (VerifyClassUsingOatFile(dex_file, klass) ||
1947 verifier::DexVerifier::VerifyClass(klass, error_msg)) {
Ian Rogersc4762272012-02-01 15:55:55 -08001948 DCHECK(!Thread::Current()->IsExceptionPending());
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001949 // Make sure all classes referenced by catch blocks are resolved
1950 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001951 klass->SetStatus(Class::kStatusVerified);
Ian Rogersc20a83e2012-01-18 18:15:32 -08001952 // Sanity check that a verified class has GC maps on all methods
1953 CheckMethodsHaveGcMaps(klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001954 } else {
Ian Rogers09f6b562012-01-31 21:58:52 -08001955 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass)
Ian Rogers1c5eb702012-02-01 09:18:34 -08001956 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
1957 << " because: " << error_msg;
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001958 Thread* self = Thread::Current();
Ian Rogersc4762272012-02-01 15:55:55 -08001959 CHECK(!self->IsExceptionPending());
Ian Rogers1c5eb702012-02-01 09:18:34 -08001960 self->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
1961 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyDescriptor(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001962 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001963 }
jeffhao98eacac2011-09-14 16:11:53 -07001964}
1965
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001966bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, Class* klass) {
1967 if (!Runtime::Current()->IsStarted()) {
1968 return false;
1969 }
1970 if (ClassLoader::UseCompileTimeClassPath()) {
1971 return false;
1972 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001973 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
1974 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001975 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001976 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001977 const char* descriptor = ClassHelper(klass).GetDescriptor();
1978 uint32_t class_def_index;
1979 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001980 CHECK(found) << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001981 UniquePtr<const OatFile::OatClass> oat_class(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001982 CHECK(oat_class.get() != NULL)
1983 << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001984 Class::Status status = oat_class->GetStatus();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001985 if (status == Class::kStatusVerified || status == Class::kStatusInitialized) {
1986 return true;
1987 }
Ian Rogersc4762272012-02-01 15:55:55 -08001988 if (status == Class::kStatusError) {
1989 // Compile time verification failed. Compile time verification can fail because we have
1990 // incomplete type information. Consider the following:
1991 // class ... {
1992 // Foo x;
1993 // .... () {
1994 // if (...) {
1995 // v1 gets assigned a type of resolved class Foo
1996 // } else {
1997 // v1 gets assigned a type of unresolved class Bar
1998 // }
1999 // iput x = v1
2000 // } }
2001 // when we merge v1 following the if-the-else it results in Conflict
2002 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
2003 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
2004 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
2005 // at compile time).
2006 return false;
2007 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002008 if (status == Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08002009 // Status is uninitialized if we couldn't determine the status at compile time, for example,
2010 // not loading the class.
2011 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
2012 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002013 return false;
2014 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002015 LOG(FATAL) << "Unexpected class status: " << status
2016 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
2017
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002018 return false;
2019}
2020
2021void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, Class* klass) {
2022 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
2023 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
2024 }
2025 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
2026 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
2027 }
2028}
2029
2030void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, Method* method) {
2031 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
2032 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
2033 if (code_item == NULL) {
2034 return; // native or abstract method
2035 }
2036 if (code_item->tries_size_ == 0) {
2037 return; // nothing to process
2038 }
2039 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
2040 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2041 ClassLinker* linker = Runtime::Current()->GetClassLinker();
2042 for (uint32_t idx = 0; idx < handlers_size; idx++) {
2043 CatchHandlerIterator iterator(handlers_ptr);
2044 for (; iterator.HasNext(); iterator.Next()) {
2045 // Ensure exception types are resolved so that they don't need resolution to be delivered,
2046 // unresolved exception types will be ignored by exception delivery
2047 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
2048 Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
2049 if (exception_type == NULL) {
2050 DCHECK(Thread::Current()->IsExceptionPending());
2051 Thread::Current()->ClearException();
2052 }
2053 }
2054 }
2055 handlers_ptr = iterator.EndDataPointer();
2056 }
2057}
2058
Ian Rogersc2b44472011-12-14 21:17:17 -08002059static void CheckProxyConstructor(Method* constructor);
2060static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
2061
Jesse Wilson95caa792011-10-12 18:14:17 -04002062Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002063 ClassLoader* loader, ObjectArray<Method>* methods,
2064 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08002065 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002066 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08002067 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04002068 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002069 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002070 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002071 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002072 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07002073 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002074 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08002075
2076 klass->SetStatus(Class::kStatusIdx);
2077
2078 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
2079
2080 // Create static field that holds throws, instance fields are inherited
2081 klass->SetSFields(AllocObjectArray<Field>(1));
2082 SirtRef<Field> sfield(AllocField());
2083 klass->SetStaticField(0, sfield.get());
2084 sfield->SetDexFieldIndex(-1);
2085 sfield->SetDeclaringClass(klass.get());
2086 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002087
Ian Rogers466bb252011-10-14 03:29:56 -07002088 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04002089 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002090 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04002091
Ian Rogers466bb252011-10-14 03:29:56 -07002092 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04002093 size_t num_virtual_methods = methods->GetLength();
2094 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
2095 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002096 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002097 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04002098 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002099
2100 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
2101 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
2102 DCHECK(!Thread::Current()->IsExceptionPending());
2103
2104 // Link the fields and virtual methods, creating vtable and iftables
2105 if (!LinkClass(klass, interfaces)) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002106 klass->SetStatus(Class::kStatusError);
Jesse Wilson95caa792011-10-12 18:14:17 -04002107 return NULL;
2108 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002109 sfield->SetObject(NULL, throws); // initialize throws field
2110 klass->SetStatus(Class::kStatusInitialized);
2111
2112 // sanity checks
2113#ifndef NDEBUG
2114 bool debug = true;
2115#else
2116 bool debug = false;
2117#endif
2118 if (debug) {
2119 CHECK(klass->GetIFields() == NULL);
2120 CheckProxyConstructor(klass->GetDirectMethod(0));
2121 for (size_t i = 0; i < num_virtual_methods; ++i) {
2122 SirtRef<Method> prototype(methods->Get(i));
2123 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
2124 }
Brian Carlstrom89521892011-12-07 22:05:07 -08002125 std::string throws_field_name("java.lang.Class[][] ");
Ian Rogersc2b44472011-12-14 21:17:17 -08002126 throws_field_name += name->ToModifiedUtf8();
2127 throws_field_name += ".throws";
2128 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
2129
2130 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
2131 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
2132 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002133 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04002134}
2135
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002136std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
2137 DCHECK(proxy_class->IsProxyClass());
2138 String* name = proxy_class->GetName();
2139 DCHECK(name != NULL);
2140 return DotToDescriptor(name->ToModifiedUtf8().c_str());
2141}
2142
2143
2144Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07002145 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07002146 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04002147 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07002148 Method* proxy_constructor = proxy_direct_methods->Get(2);
2149 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
2150 // code_ too)
2151 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
2152 // Make this constructor public and fix the class to be our Proxy version
2153 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002154 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08002155 return constructor;
2156}
2157
2158static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07002159 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002160 MethodHelper mh(constructor);
2161 CHECK_STREQ(mh.GetName(), "<init>");
Elliott Hughesba8eee12012-01-24 20:25:24 -08002162 CHECK_EQ(mh.GetSignature(), std::string("(Ljava/lang/reflect/InvocationHandler;)V"));
Ian Rogers466bb252011-10-14 03:29:56 -07002163 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04002164}
2165
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002166Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
2167 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
2168 // prototype method
2169 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
2170 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07002171 // as necessary
2172 Method* method = down_cast<Method*>(prototype->Clone());
2173
2174 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
2175 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002176 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07002177 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002178
Ian Rogers466bb252011-10-14 03:29:56 -07002179 // At runtime the method looks like a reference and argument saving method, clone the code
2180 // related parameters from this method.
2181 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
2182 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
2183 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
2184 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
2185 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08002186 return method;
2187}
Jesse Wilson95caa792011-10-12 18:14:17 -04002188
Ian Rogersc2b44472011-12-14 21:17:17 -08002189static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07002190 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002191 CHECK(!prototype->IsFinal());
2192 CHECK(method->IsFinal());
2193 CHECK(!method->IsAbstract());
2194 MethodHelper mh(method);
2195 const char* method_name = mh.GetName();
2196 const char* method_shorty = mh.GetShorty();
2197 Class* method_return = mh.GetReturnType();
2198
2199 mh.ChangeMethod(prototype.get());
2200
2201 CHECK_STREQ(mh.GetName(), method_name);
2202 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07002203
2204 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002205 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04002206}
2207
Brian Carlstrom25c33252011-09-18 15:58:35 -07002208bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002209 CHECK(klass->IsResolved() || klass->IsErroneous())
2210 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002211
Carl Shapirob5573532011-07-12 18:22:59 -07002212 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002213
Brian Carlstrom25c33252011-09-18 15:58:35 -07002214 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002215 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002216 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002217 ObjectLock lock(klass);
2218
Brian Carlstromd1422f82011-09-28 11:37:09 -07002219 if (klass->GetStatus() == Class::kStatusInitialized) {
2220 return true;
2221 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002222
Brian Carlstromd1422f82011-09-28 11:37:09 -07002223 if (klass->IsErroneous()) {
2224 ThrowEarlierClassFailure(klass);
2225 return false;
2226 }
2227
2228 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07002229 VerifyClass(klass);
2230 if (klass->GetStatus() != Class::kStatusVerified) {
Ian Rogers595799e2012-01-11 17:32:51 -08002231 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002232 return false;
2233 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002234 }
2235
Brian Carlstrom25c33252011-09-18 15:58:35 -07002236 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
2237 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002238 // if the class has a <clinit> but we can't run it during compilation,
Ian Rogers595799e2012-01-11 17:32:51 -08002239 // don't bother going to kStatusInitializing. We return true to maintain
2240 // the invariant that a false result implies there is a pending exception.
2241 return true;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002242 }
2243
Brian Carlstromd1422f82011-09-28 11:37:09 -07002244 // If the class is kStatusInitializing, either this thread is
2245 // initializing higher up the stack or another thread has beat us
2246 // to initializing and we need to wait. Either way, this
2247 // invocation of InitializeClass will not be responsible for
2248 // running <clinit> and will return.
2249 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002250 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002251 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002252 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002253 return true;
2254 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002255 // No. That's fine. Wait for another thread to finish initializing.
2256 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002257 }
2258
2259 if (!ValidateSuperClassDescriptors(klass)) {
2260 klass->SetStatus(Class::kStatusError);
2261 return false;
2262 }
2263
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002264 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified) << PrettyClass(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002265
Elliott Hughesdcc24742011-09-07 14:02:44 -07002266 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002267 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002268 }
2269
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002270 uint64_t t0 = NanoTime();
2271
Brian Carlstrom25c33252011-09-18 15:58:35 -07002272 if (!InitializeSuperClass(klass, can_run_clinit)) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002273 CHECK(klass->IsErroneous());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002274 return false;
2275 }
2276
2277 InitializeStaticFields(klass);
2278
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002279 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002280 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002281 }
2282
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002283 uint64_t t1 = NanoTime();
2284
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002285 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002286 {
2287 ObjectLock lock(klass);
2288
2289 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002290 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002291 klass->SetStatus(Class::kStatusError);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002292 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002293 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002294 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2295 RuntimeStats* thread_stats = self->GetStats();
2296 ++global_stats->class_init_count;
2297 ++thread_stats->class_init_count;
2298 global_stats->class_init_time_ns += (t1 - t0);
2299 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002300 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002301 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002302 ClassHelper kh(klass);
2303 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002304 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002305 }
2306 lock.NotifyAll();
2307 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002308 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002309}
2310
Brian Carlstromd1422f82011-09-28 11:37:09 -07002311bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
2312 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002313 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002314 lock.Wait();
2315
2316 // When we wake up, repeat the test for init-in-progress. If
2317 // there's an exception pending (only possible if
2318 // "interruptShouldThrow" was set), bail out.
2319 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002320 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002321 klass->SetStatus(Class::kStatusError);
2322 return false;
2323 }
2324 // Spurious wakeup? Go back to waiting.
2325 if (klass->GetStatus() == Class::kStatusInitializing) {
2326 continue;
2327 }
2328 if (klass->IsErroneous()) {
2329 // The caller wants an exception, but it was thrown in a
2330 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002331 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002332 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002333 return false;
2334 }
2335 if (klass->IsInitialized()) {
2336 return true;
2337 }
2338 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2339 }
2340 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2341}
2342
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002343bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2344 if (klass->IsInterface()) {
2345 return true;
2346 }
2347 // begin with the methods local to the superclass
2348 if (klass->HasSuperClass() &&
2349 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2350 const Class* super = klass->GetSuperClass();
Ian Rogers595799e2012-01-11 17:32:51 -08002351 for (int i = super->GetVTable()->GetLength() - 1; i >= 0; --i) {
2352 const Method* method = klass->GetVTable()->Get(i);
2353 if (method != super->GetVTable()->Get(i) &&
2354 !IsSameMethodSignatureInDifferentClassContexts(method, super, klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002355 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2356 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2357 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002358 return false;
2359 }
2360 }
2361 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002362 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2363 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2364 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002365 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2366 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002367 const Method* method = interface_entry->GetMethodArray()->Get(j);
Ian Rogers595799e2012-01-11 17:32:51 -08002368 if (!IsSameMethodSignatureInDifferentClassContexts(method, interface,
2369 method->GetDeclaringClass())) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002370 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2371 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2372 PrettyMethod(method).c_str(),
2373 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002374 return false;
2375 }
2376 }
2377 }
2378 }
2379 return true;
2380}
2381
Ian Rogers595799e2012-01-11 17:32:51 -08002382// Returns true if classes referenced by the signature of the method are the
2383// same classes in klass1 as they are in klass2.
2384bool ClassLinker::IsSameMethodSignatureInDifferentClassContexts(const Method* method,
2385 const Class* klass1,
2386 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002387 if (klass1 == klass2) {
2388 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002389 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002390 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002391 const DexFile::ProtoId& proto_id =
2392 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002393 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2394 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002395 if (descriptor == NULL) {
2396 break;
2397 }
2398 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2399 // Found a non-primitive type.
Ian Rogers595799e2012-01-11 17:32:51 -08002400 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002401 return false;
2402 }
2403 }
2404 }
2405 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002406 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002407 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Ian Rogers595799e2012-01-11 17:32:51 -08002408 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002409 return false;
2410 }
2411 }
2412 return true;
2413}
2414
Ian Rogers595799e2012-01-11 17:32:51 -08002415// Returns true if the descriptor resolves to the same class in the context of klass1 and klass2.
2416bool ClassLinker::IsSameDescriptorInDifferentClassContexts(const char* descriptor,
2417 const Class* klass1,
2418 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002419 CHECK(descriptor != NULL);
2420 CHECK(klass1 != NULL);
2421 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002422 if (klass1 == klass2) {
2423 return true;
2424 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002425 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Ian Rogers595799e2012-01-11 17:32:51 -08002426 if (found1 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002427 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002428 }
Ian Rogers595799e2012-01-11 17:32:51 -08002429 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
2430 if (found2 == NULL) {
2431 Thread::Current()->ClearException();
2432 }
2433 return found1 == found2;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002434}
2435
Brian Carlstrom25c33252011-09-18 15:58:35 -07002436bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002437 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002438 if (!klass->IsInterface() && klass->HasSuperClass()) {
2439 Class* super_class = klass->GetSuperClass();
2440 if (super_class->GetStatus() != Class::kStatusInitialized) {
2441 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002442 Thread* self = Thread::Current();
2443 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002444 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002445 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002446 // TODO: check for a pending exception
2447 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002448 if (!can_run_clinit) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002449 // Don't set status to error when we can't run <clinit>.
2450 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing) << PrettyClass(klass);
2451 klass->SetStatus(Class::kStatusVerified);
2452 return false;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002453 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002454 klass->SetStatus(Class::kStatusError);
2455 klass->NotifyAll();
2456 return false;
2457 }
2458 }
2459 }
2460 return true;
2461}
2462
Brian Carlstrom25c33252011-09-18 15:58:35 -07002463bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002464 CHECK(c != NULL);
2465 if (c->IsInitialized()) {
2466 return true;
2467 }
2468
Elliott Hughes5f791332011-09-15 17:45:30 -07002469 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002470 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Ian Rogers595799e2012-01-11 17:32:51 -08002471 bool success = InitializeClass(c, can_run_clinit);
2472 if (!success) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002473 CHECK(self->IsExceptionPending()) << PrettyClass(c);
Ian Rogers595799e2012-01-11 17:32:51 -08002474 }
2475 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002476}
2477
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002478void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002479 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002480 const ClassLoader* cl = c->GetClassLoader();
2481 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002482 ClassDataItemIterator it(dex_file, class_data);
2483 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2484 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002485 }
2486}
2487
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002488void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002489 size_t num_static_fields = klass->NumStaticFields();
2490 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002491 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002492 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002493 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002494 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002495 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002496 return;
2497 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002498 ClassHelper kh(klass);
2499 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002500 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002501 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002502 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002503
Ian Rogers0571d352011-11-03 19:51:38 -07002504 if (it.HasNext()) {
2505 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2506 std::map<uint32_t, Field*> field_map;
2507 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2508 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2509 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002510 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002511 }
2512}
2513
Ian Rogersc2b44472011-12-14 21:17:17 -08002514bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002515 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002516 if (!LinkSuperClass(klass)) {
2517 return false;
2518 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002519 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002520 return false;
2521 }
2522 if (!LinkInstanceFields(klass)) {
2523 return false;
2524 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002525 if (!LinkStaticFields(klass)) {
2526 return false;
2527 }
2528 CreateReferenceInstanceOffsets(klass);
2529 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002530 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2531 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002532 return true;
2533}
2534
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002535bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002536 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002537 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2538 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
Ian Rogerscab01012012-01-10 17:35:46 -08002539 CHECK(class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002540 uint16_t super_class_idx = class_def->superclass_idx_;
2541 if (super_class_idx != DexFile::kDexNoIndex16) {
2542 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002543 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002544 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002545 return false;
2546 }
Ian Rogersbe125a92012-01-11 15:19:49 -08002547 // Verify
2548 if (!klass->CanAccess(super_class)) {
2549 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2550 "Class %s extended by class %s is inaccessible",
2551 PrettyDescriptor(super_class).c_str(),
2552 PrettyDescriptor(klass.get()).c_str());
2553 return false;
2554 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002555 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002556 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002557 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2558 if (interfaces != NULL) {
2559 for (size_t i = 0; i < interfaces->Size(); i++) {
2560 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2561 Class* interface = ResolveType(dex_file, idx, klass.get());
2562 if (interface == NULL) {
2563 DCHECK(Thread::Current()->IsExceptionPending());
2564 return false;
2565 }
2566 // Verify
2567 if (!klass->CanAccess(interface)) {
2568 // TODO: the RI seemed to ignore this in my testing.
2569 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2570 "Interface %s implemented by class %s is inaccessible",
2571 PrettyDescriptor(interface).c_str(),
2572 PrettyDescriptor(klass.get()).c_str());
2573 return false;
2574 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002575 }
2576 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002577 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002578 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002579 return true;
2580}
2581
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002582bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002583 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002584 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002585 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002586 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002587 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002588 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002589 return false;
2590 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002591 return true;
2592 }
2593 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002594 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002595 return false;
2596 }
2597 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002598 if (super->IsFinal() || super->IsInterface()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002599 Thread* self = Thread::Current();
2600 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002601 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002602 PrettyDescriptor(super).c_str(),
2603 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002604 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002605 return false;
2606 }
2607 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002608 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002609 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002610 PrettyDescriptor(super).c_str(),
2611 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002612 return false;
2613 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002614
2615 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2616 if (super->IsFinalizable()) {
2617 klass->SetFinalizable();
2618 }
2619
Elliott Hughes2da50362011-10-10 16:57:08 -07002620 // Inherit reference flags (if any) from the superclass.
2621 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2622 if (reference_flags != 0) {
2623 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2624 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002625 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002626 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002627 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002628 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002629 return false;
2630 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002631
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002632#ifndef NDEBUG
2633 // Ensure super classes are fully resolved prior to resolving fields..
2634 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002635 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002636 super = super->GetSuperClass();
2637 }
2638#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002639 return true;
2640}
2641
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002642// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002643bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002644 if (klass->IsInterface()) {
2645 // No vtable.
2646 size_t count = klass->NumVirtualMethods();
2647 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002648 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002649 return false;
2650 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002651 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002652 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002653 }
jeffhaobdb76512011-09-07 11:43:16 -07002654 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002655 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002656 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002657 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002658 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002659 }
2660 return true;
2661}
2662
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002663bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002664 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002665 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2666 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002667 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002668 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002669 SirtRef<ObjectArray<Method> > vtable(klass->GetSuperClass()->GetVTable()->CopyOf(max_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002670 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002671 MethodHelper local_mh(NULL, this);
2672 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002673 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002674 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002675 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002676 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002677 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002678 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002679 super_mh.ChangeMethod(super_method);
2680 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002681 // Verify
2682 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002683 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002684 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002685 PrettyDescriptor(klass.get()).c_str(),
2686 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002687 return false;
2688 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002689 vtable->Set(j, local_method);
2690 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002691 break;
2692 }
2693 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002694 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002695 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002696 vtable->Set(actual_count, local_method);
2697 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002698 actual_count += 1;
2699 }
2700 }
2701 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002702 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002703 return false;
2704 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002705 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002706 CHECK_LE(actual_count, max_count);
2707 if (actual_count < max_count) {
Ian Rogers30fab402012-01-23 15:43:46 -08002708 vtable.reset(vtable->CopyOf(actual_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002709 }
Ian Rogers30fab402012-01-23 15:43:46 -08002710 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002711 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002712 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002713 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002714 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002715 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002716 return false;
2717 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002718 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002719 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002720 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2721 vtable->Set(i, virtual_method);
2722 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002723 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002724 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002725 }
2726 return true;
2727}
2728
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002729bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002730 size_t super_ifcount;
2731 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002732 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002733 } else {
2734 super_ifcount = 0;
2735 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002736 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002737 ClassHelper kh(klass.get(), this);
2738 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2739 ifcount += num_interfaces;
2740 for (size_t i = 0; i < num_interfaces; i++) {
2741 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2742 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002743 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002744 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002745 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002746 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002747 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002748 return true;
2749 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002750 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002751 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002752 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2753 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogersb52b01a2012-01-12 17:01:38 -08002754 Class* super_interface = super_iftable->Get(i)->GetInterface();
2755 iftable->Set(i, AllocInterfaceEntry(super_interface));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002756 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002757 }
2758 // Flatten the interface inheritance hierarchy.
2759 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002760 for (size_t i = 0; i < num_interfaces; i++) {
2761 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002762 DCHECK(interface != NULL);
2763 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002764 ClassHelper ih(interface);
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002765 Thread* self = Thread::Current();
2766 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002767 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002768 PrettyDescriptor(klass.get()).c_str(),
2769 PrettyDescriptor(ih.GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002770 return false;
2771 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002772 // Check if interface is already in iftable
2773 bool duplicate = false;
2774 for (size_t j = 0; j < idx; j++) {
2775 Class* existing_interface = iftable->Get(j)->GetInterface();
2776 if (existing_interface == interface) {
2777 duplicate = true;
2778 break;
2779 }
2780 }
2781 if (!duplicate) {
2782 // Add this non-duplicate interface.
2783 iftable->Set(idx++, AllocInterfaceEntry(interface));
2784 // Add this interface's non-duplicate super-interfaces.
2785 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2786 Class* super_interface = interface->GetIfTable()->Get(j)->GetInterface();
2787 bool super_duplicate = false;
2788 for (size_t k = 0; k < idx; k++) {
2789 Class* existing_interface = iftable->Get(k)->GetInterface();
2790 if (existing_interface == super_interface) {
2791 super_duplicate = true;
2792 break;
2793 }
2794 }
2795 if (!super_duplicate) {
2796 iftable->Set(idx++, AllocInterfaceEntry(super_interface));
2797 }
2798 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002799 }
2800 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002801 // Shrink iftable in case duplicates were found
2802 if (idx < ifcount) {
2803 iftable.reset(iftable->CopyOf(idx));
2804 ifcount = idx;
2805 } else {
2806 CHECK_EQ(idx, ifcount);
2807 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002808 klass->SetIfTable(iftable.get());
Elliott Hughes4681c802011-09-25 18:04:37 -07002809
2810 // If we're an interface, we don't need the vtable pointers, so we're done.
2811 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002812 return true;
2813 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002814 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002815 MethodHelper vtable_mh(NULL, this);
2816 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002817 for (size_t i = 0; i < ifcount; ++i) {
2818 InterfaceEntry* interface_entry = iftable->Get(i);
2819 Class* interface = interface_entry->GetInterface();
2820 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2821 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002822 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002823 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2824 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002825 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002826 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002827 // For each method listed in the interface's method list, find the
2828 // matching method in our class's method list. We want to favor the
2829 // subclass over the superclass, which just requires walking
2830 // back from the end of the vtable. (This only matters if the
2831 // superclass defines a private method and this class redefines
2832 // it -- otherwise it would use the same vtable slot. In .dex files
2833 // those don't end up in the virtual method table, so it shouldn't
2834 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002835 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2836 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002837 vtable_mh.ChangeMethod(vtable_method);
2838 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002839 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002840 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002841 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002842 return false;
2843 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002844 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002845 break;
2846 }
2847 }
2848 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002849 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002850 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002851 Method* mir_method = miranda_list[mir];
2852 vtable_mh.ChangeMethod(mir_method);
2853 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002854 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002855 break;
2856 }
2857 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002858 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002859 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002860 miranda_method.reset(AllocMethod());
2861 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2862 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002863 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002864 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002865 }
2866 }
2867 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002868 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002869 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002870 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002871 klass->SetVirtualMethods((old_method_count == 0)
2872 ? AllocObjectArray<Method>(new_method_count)
2873 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002874
Ian Rogers30fab402012-01-23 15:43:46 -08002875 SirtRef<ObjectArray<Method> > vtable(klass->GetVTableDuringLinking());
2876 CHECK(vtable.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002877 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002878 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers30fab402012-01-23 15:43:46 -08002879 vtable.reset(vtable->CopyOf(new_vtable_count));
Elliott Hughes4681c802011-09-25 18:04:37 -07002880 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002881 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002882 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002883 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2884 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2885 klass->SetVirtualMethod(old_method_count + i, method);
2886 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002887 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002888 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002889 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002890 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002891
2892 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2893 for (int i = 0; i < vtable->GetLength(); ++i) {
2894 CHECK(vtable->Get(i) != NULL);
2895 }
2896
2897// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2898
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002899 return true;
2900}
2901
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002902bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2903 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002904 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002905}
2906
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002907bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2908 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002909 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002910 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002911 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002912 return success;
2913}
2914
Brian Carlstromdbc05252011-09-09 01:59:59 -07002915struct LinkFieldsComparator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002916 explicit LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002917 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002918 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002919 fh_->ChangeField(field1);
2920 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2921 fh_->ChangeField(field2);
2922 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002923 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2924 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2925 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2926 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002927 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2928 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2929 if (order1 != order2) {
2930 return order1 < order2;
2931 }
2932
2933 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002934 fh_->ChangeField(field1);
2935 StringPiece name1(fh_->GetName());
2936 fh_->ChangeField(field2);
2937 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002938 return name1 < name2;
2939 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002940
2941 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002942};
2943
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002944bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002945 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002946 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002947
2948 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002949 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002950
2951 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002952 size_t size;
2953 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002954 if (is_static) {
2955 size = klass->GetClassSize();
2956 field_offset = Class::FieldsOffset();
2957 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002958 Class* super_class = klass->GetSuperClass();
2959 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002960 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002961 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002962 }
2963 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002964 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002965
Brian Carlstromdbc05252011-09-09 01:59:59 -07002966 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002967
Brian Carlstromdbc05252011-09-09 01:59:59 -07002968 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002969 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002970 std::deque<Field*> grouped_and_sorted_fields;
2971 for (size_t i = 0; i < num_fields; i++) {
2972 grouped_and_sorted_fields.push_back(fields->Get(i));
2973 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002974 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002975 std::sort(grouped_and_sorted_fields.begin(),
2976 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002977 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002978
2979 // References should be at the front.
2980 size_t current_field = 0;
2981 size_t num_reference_fields = 0;
2982 for (; current_field < num_fields; current_field++) {
2983 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002984 fh.ChangeField(field);
2985 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002986 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002987 if (isPrimitive) {
2988 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002989 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002990 grouped_and_sorted_fields.pop_front();
2991 num_reference_fields++;
2992 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002993 field->SetOffset(field_offset);
2994 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002995 }
2996
2997 // Now we want to pack all of the double-wide fields together. If
2998 // we're not aligned, though, we want to shuffle one 32-bit field
2999 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07003000 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003001 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
3002 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003003 fh.ChangeField(field);
3004 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003005 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
3006 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003007 continue;
3008 }
3009 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003010 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003011 // drop the consumed field
3012 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
3013 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003014 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07003015 // whether we found a 32-bit field for padding or not, we advance
3016 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003017 }
3018
3019 // Alignment is good, shuffle any double-wide fields forward, and
3020 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07003021 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07003022 while (!grouped_and_sorted_fields.empty()) {
3023 Field* field = grouped_and_sorted_fields.front();
3024 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003025 fh.ChangeField(field);
3026 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003027 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07003028 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003029 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003030 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003031 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07003032 ? sizeof(uint64_t)
3033 : sizeof(uint32_t)));
3034 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003035 }
3036
Elliott Hughesadb460d2011-10-05 17:02:34 -07003037 // 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 -08003038 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
3039 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07003040 // We know there are no non-reference fields in the Reference classes, and we know
3041 // that 'referent' is alphabetically last, so this is easy...
3042 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003043 fh.ChangeField(fields->Get(num_fields - 1));
Elliott Hughesba8eee12012-01-24 20:25:24 -08003044 CHECK_STREQ(fh.GetName(), "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07003045 --num_reference_fields;
3046 }
3047
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003048#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07003049 // Make sure that all reference fields appear before
3050 // non-reference fields, and all double-wide fields are aligned.
3051 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07003052 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003053 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003054 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003055 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003056 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07003057 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07003058 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
3059 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003060 fh.ChangeField(field);
3061 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003062 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003063 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07003064 is_primitive = true; // We lied above, so we have to expect a lie here.
3065 }
3066 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07003067 if (!seen_non_ref) {
3068 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003069 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003070 }
Brian Carlstrombe977852011-07-19 14:54:54 -07003071 } else {
3072 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003073 }
3074 }
Brian Carlstrombe977852011-07-19 14:54:54 -07003075 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003076 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003077 }
3078#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003079 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003080 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003081 if (is_static) {
3082 klass->SetNumReferenceStaticFields(num_reference_fields);
3083 klass->SetClassSize(size);
3084 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003085 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003086 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003087 klass->SetObjectSize(size);
3088 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003089 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003090 return true;
3091}
3092
3093// Set the bitmap of reference offsets, refOffsets, from the ifields
3094// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003095void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003096 uint32_t reference_offsets = 0;
3097 Class* super_class = klass->GetSuperClass();
3098 if (super_class != NULL) {
3099 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003100 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003101 if (reference_offsets == CLASS_WALK_SUPER) {
3102 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003103 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003104 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003105 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003106 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003107}
3108
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003109void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003110 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003111}
3112
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003113void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003114 uint32_t reference_offsets) {
3115 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003116 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
3117 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003118 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003119 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003120 // All of the fields that contain object references are guaranteed
3121 // to be at the beginning of the fields list.
3122 for (size_t i = 0; i < num_reference_fields; ++i) {
3123 // Note that byte_offset is the offset from the beginning of
3124 // object, not the offset into instance data
3125 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003126 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003127 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
3128 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
3129 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07003130 CHECK_NE(new_bit, 0U);
3131 reference_offsets |= new_bit;
3132 } else {
3133 reference_offsets = CLASS_WALK_SUPER;
3134 break;
3135 }
3136 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003137 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003138 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003139 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003140 } else {
3141 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003142 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003143}
3144
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003145String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07003146 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003147 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003148 if (resolved != NULL) {
3149 return resolved;
3150 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003151 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
3152 int32_t utf16_length = dex_file.GetStringLength(string_id);
3153 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07003154 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003155 dex_cache->SetResolvedString(string_idx, string);
3156 return string;
3157}
3158
3159Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003160 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003161 DexCache* dex_cache,
3162 const ClassLoader* class_loader) {
3163 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003164 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07003165 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003166 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003167 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05003168 // TODO: we used to throw here if resolved's class loader was not the
3169 // boot class loader. This was to permit different classes with the
3170 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003171 dex_cache->SetResolvedType(type_idx, resolved);
3172 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08003173 CHECK(Thread::Current()->IsExceptionPending())
3174 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003175 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003176 }
3177 return resolved;
3178}
3179
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003180Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
3181 uint32_t method_idx,
3182 DexCache* dex_cache,
3183 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003184 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003185 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
3186 if (resolved != NULL) {
3187 return resolved;
3188 }
3189 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3190 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
3191 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07003192 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003193 return NULL;
3194 }
3195
Ian Rogers0571d352011-11-03 19:51:38 -07003196 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
3197 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003198 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003199 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003200 } else if (klass->IsInterface()) {
3201 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003202 } else {
3203 resolved = klass->FindVirtualMethod(name, signature);
3204 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003205 if (resolved != NULL) {
3206 dex_cache->SetResolvedMethod(method_idx, resolved);
3207 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003208 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003209 }
3210 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003211}
3212
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003213Field* ClassLinker::ResolveField(const DexFile& dex_file,
3214 uint32_t field_idx,
3215 DexCache* dex_cache,
3216 const ClassLoader* class_loader,
3217 bool is_static) {
3218 Field* resolved = dex_cache->GetResolvedField(field_idx);
3219 if (resolved != NULL) {
3220 return resolved;
3221 }
3222 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3223 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3224 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003225 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003226 return NULL;
3227 }
3228
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003229 const char* name = dex_file.GetFieldName(field_id);
3230 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003231 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003232 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003233 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003234 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003235 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003236 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003237 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003238 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08003239 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
3240 }
3241 return resolved;
3242}
3243
3244Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
3245 uint32_t field_idx,
3246 DexCache* dex_cache,
3247 const ClassLoader* class_loader) {
3248 Field* resolved = dex_cache->GetResolvedField(field_idx);
3249 if (resolved != NULL) {
3250 return resolved;
3251 }
3252 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3253 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3254 if (klass == NULL) {
3255 DCHECK(Thread::Current()->IsExceptionPending());
3256 return NULL;
3257 }
3258
3259 const char* name = dex_file.GetFieldName(field_id);
3260 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3261 resolved = klass->FindField(name, type);
3262 if (resolved != NULL) {
3263 dex_cache->SetResolvedField(field_idx, resolved);
3264 } else {
3265 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003266 }
3267 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07003268}
3269
Ian Rogersad25ac52011-10-04 19:13:33 -07003270const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
3271 Class* declaring_class = referrer->GetDeclaringClass();
3272 DexCache* dex_cache = declaring_class->GetDexCache();
3273 const DexFile& dex_file = FindDexFile(dex_cache);
3274 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3275 return dex_file.GetShorty(method_id.proto_idx_);
3276}
3277
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003278void ClassLinker::DumpAllClasses(int flags) const {
3279 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3280 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3281 std::vector<Class*> all_classes;
3282 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003283 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003284 typedef Table::const_iterator It; // TODO: C++0x auto
3285 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3286 all_classes.push_back(it->second);
3287 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003288 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3289 all_classes.push_back(it->second);
3290 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003291 }
3292
3293 for (size_t i = 0; i < all_classes.size(); ++i) {
3294 all_classes[i]->DumpClass(std::cerr, flags);
3295 }
3296}
3297
Elliott Hughescac6cc72011-11-03 20:31:21 -07003298void ClassLinker::DumpForSigQuit(std::ostream& os) const {
3299 MutexLock mu(classes_lock_);
3300 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3301 << classes_.size() << " allocated classes\n";
3302}
3303
Elliott Hughese27955c2011-08-26 15:21:24 -07003304size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003305 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003306 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003307}
3308
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003309pid_t ClassLinker::GetClassesLockOwner() {
3310 return classes_lock_.GetOwner();
3311}
3312
3313pid_t ClassLinker::GetDexLockOwner() {
3314 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003315}
3316
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003317void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3318 DCHECK(!init_done_);
3319
3320 DCHECK(klass != NULL);
3321 DCHECK(klass->GetClassLoader() == NULL);
3322
3323 DCHECK(class_roots_ != NULL);
3324 DCHECK(class_roots_->Get(class_root) == NULL);
3325 class_roots_->Set(class_root, klass);
3326}
3327
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003328} // namespace art