blob: 9d53f9395a4be98709ef0bf533573c58984d55e6 [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 Carlstroma56fcd62012-02-04 21:23:01 -0800571 std::string dex2oat_string(GetAndroidRoot());
572 dex2oat_string += "/bin/dex2oat";
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800573#ifndef NDEBUG
574 dex2oat_string += 'd';
575#endif
576 const char* dex2oat = dex2oat_string.c_str();
577
578 const char* class_path = Runtime::Current()->GetClassPath().c_str();
579
580 std::string boot_image_option_string("--boot-image=");
Ian Rogers30fab402012-01-23 15:43:46 -0800581 boot_image_option_string += Heap::GetSpaces()[0]->AsImageSpace()->GetImageFilename();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800582 const char* boot_image_option = boot_image_option_string.c_str();
583
584 std::string dex_file_option_string("--dex-file=");
Brian Carlstromd601af82012-01-06 10:15:19 -0800585 dex_file_option_string += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800586 const char* dex_file_option = dex_file_option_string.c_str();
587
Brian Carlstromd601af82012-01-06 10:15:19 -0800588 std::string oat_fd_option_string("--oat-fd=");
Brian Carlstrom866c8622012-01-06 16:35:13 -0800589 StringAppendF(&oat_fd_option_string, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800590 const char* oat_fd_option = oat_fd_option_string.c_str();
591
592 std::string oat_name_option_string("--oat-name=");
593 oat_name_option_string += oat_cache_filename;
594 const char* oat_name_option = oat_name_option_string.c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800595
jeffhao262bf462011-10-20 18:36:32 -0700596 // fork and exec dex2oat
597 pid_t pid = fork();
598 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800599 // no allocation allowed between fork and exec
Ian Rogers725aee52012-01-11 11:56:56 -0800600
601 // change process groups, so we don't get reaped by ProcessManager
602 setpgid(0, 0);
603
jeffhao10037c82012-01-23 15:06:23 -0800604 VLOG(class_linker) << dex2oat
605 << " --runtime-arg -Xms64m"
606 << " --runtime-arg -Xmx64m"
607 << " --runtime-arg -classpath"
608 << " --runtime-arg " << class_path
609 << " " << boot_image_option
610 << " " << dex_file_option
611 << " " << oat_fd_option
612 << " " << oat_name_option;
613
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800614 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700615 "--runtime-arg", "-Xms64m",
616 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500617 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800618 "--runtime-arg", class_path,
619 boot_image_option,
620 dex_file_option,
Brian Carlstromd601af82012-01-06 10:15:19 -0800621 oat_fd_option,
622 oat_name_option,
jeffhao262bf462011-10-20 18:36:32 -0700623 NULL);
624
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800625 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
Brian Carlstromd601af82012-01-06 10:15:19 -0800626 return false;
jeffhao262bf462011-10-20 18:36:32 -0700627 } else {
628 // wait for dex2oat to finish
629 int status;
630 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
631 if (got_pid != pid) {
632 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
Brian Carlstromd601af82012-01-06 10:15:19 -0800633 return false;
jeffhao262bf462011-10-20 18:36:32 -0700634 }
635 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800636 LOG(ERROR) << dex2oat << " failed with dex-file=" << dex_filename;
637 return false;
jeffhao262bf462011-10-20 18:36:32 -0700638 }
639 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800640 return true;
jeffhao262bf462011-10-20 18:36:32 -0700641}
642
Brian Carlstrom866c8622012-01-06 16:35:13 -0800643void ClassLinker::RegisterOatFile(const OatFile& oat_file) {
644 MutexLock mu(dex_lock_);
645 RegisterOatFileLocked(oat_file);
646}
647
648void ClassLinker::RegisterOatFileLocked(const OatFile& oat_file) {
649 dex_lock_.AssertHeld();
650 oat_files_.push_back(&oat_file);
651}
652
Ian Rogers30fab402012-01-23 15:43:46 -0800653OatFile* ClassLinker::OpenOat(const ImageSpace* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700654 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700655 const Runtime* runtime = Runtime::Current();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700656 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800657 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
658 // check the down cast
659 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700660 std::string oat_filename;
661 oat_filename += runtime->GetHostPrefix();
662 oat_filename += oat_location->ToModifiedUtf8();
Ian Rogers30fab402012-01-23 15:43:46 -0800663 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBegin());
664 VLOG(startup) << "ClassLinker::OpenOat entering oat_filename=" << oat_filename;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700665 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700666 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700667 return NULL;
668 }
669 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
670 uint32_t image_oat_checksum = image_header.GetOatChecksum();
671 if (oat_checksum != image_oat_checksum) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800672 LOG(ERROR) << "Failed to match oat file checksum " << std::hex << oat_checksum
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700673 << " to expected oat checksum " << std::hex << oat_checksum
674 << " in image";
675 return NULL;
676 }
Brian Carlstrom866c8622012-01-06 16:35:13 -0800677 RegisterOatFileLocked(*oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800678 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700679 return oat_file;
680}
681
Brian Carlstromae826982011-11-09 01:33:42 -0800682const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800683 return FindOpenedOatFileFromDexLocation(dex_file.GetLocation(),
684 dex_file.GetLocationChecksum());
685}
686
687const OatFile* ClassLinker::FindOpenedOatFileFromDexLocation(const std::string& dex_location,
688 uint32_t dex_location_checksum) {
Brian Carlstromae826982011-11-09 01:33:42 -0800689 for (size_t i = 0; i < oat_files_.size(); i++) {
690 const OatFile* oat_file = oat_files_[i];
691 DCHECK(oat_file != NULL);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800692 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, false);
693 if (oat_dex_file != NULL
694 && oat_dex_file->GetDexFileLocationChecksum() == dex_location_checksum) {
Brian Carlstromae826982011-11-09 01:33:42 -0800695 return oat_file;
696 }
697 }
698 return NULL;
699}
700
Brian Carlstromd601af82012-01-06 10:15:19 -0800701class LockedFd {
702 public:
703 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
704 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
705 if (fd == -1) {
706 PLOG(ERROR) << "Failed to open file '" << name << "'";
707 return NULL;
708 }
709 fchmod(fd, mode);
710
711 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
712 // try to lock non-blocking so we can log if we need may need to block
713 int result = flock(fd, LOCK_EX | LOCK_NB);
714 if (result == -1) {
715 LOG(WARNING) << "sleeping while locking file " << name;
716 // retry blocking
717 result = flock(fd, LOCK_EX);
718 }
719 if (result == -1) {
720 PLOG(ERROR) << "Failed to lock file '" << name << "'";
721 close(fd);
722 return NULL;
723 }
724 return new LockedFd(fd);
725 }
726
727 int GetFd() const {
728 return fd_;
729 }
730
731 ~LockedFd() {
732 if (fd_ != -1) {
733 int result = flock(fd_, LOCK_UN);
734 if (result == -1) {
735 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
736 }
737 close(fd_);
738 }
739 }
740
741 private:
742 explicit LockedFd(int fd) : fd_(fd) {}
743
744 int fd_;
745};
746
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800747static const DexFile* FindDexFileInOatLocation(const std::string& dex_location,
748 uint32_t dex_location_checksum,
749 const std::string& oat_location) {
750 UniquePtr<OatFile> oat_file(OatFile::Open(oat_location, "", NULL));
751 if (oat_file.get() == NULL) {
752 return NULL;
753 }
754 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
755 if (oat_dex_file == NULL) {
756 return NULL;
757 }
758 if (oat_dex_file->GetDexFileLocationChecksum() != dex_location_checksum) {
759 return NULL;
760 }
761 Runtime::Current()->GetClassLinker()->RegisterOatFile(*oat_file.release());
762 return oat_dex_file->OpenDexFile();
763}
764
765const DexFile* ClassLinker::FindOrCreateOatFileForDexLocation(const std::string& dex_location,
766 const std::string& oat_location) {
767 uint32_t dex_location_checksum;
768 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) {
769 LOG(ERROR) << "Failed to compute checksum '" << dex_location << "'";
770 return NULL;
771 }
772
773 // Check if we already have an up-to-date output file
774 const DexFile* dex_file = FindDexFileInOatLocation(dex_location,
775 dex_location_checksum,
776 oat_location);
777 if (dex_file != NULL) {
778 return dex_file;
779 }
780
781 // Generate the output oat file for the dex file
782 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
783 UniquePtr<File> file(OS::OpenFile(oat_location.c_str(), true));
784 if (file.get() == NULL) {
785 LOG(ERROR) << "Failed to create oat file: " << oat_location;
786 return NULL;
787 }
788 if (!class_linker->GenerateOatFile(dex_location, file->Fd(), oat_location)) {
789 LOG(ERROR) << "Failed to generate oat file: " << oat_location;
790 return NULL;
791 }
792 // Open the oat from file descriptor we passed to GenerateOatFile
793 if (lseek(file->Fd(), 0, SEEK_SET) != 0) {
794 LOG(ERROR) << "Failed to seek to start of generated oat file: " << oat_location;
795 return NULL;
796 }
797 const OatFile* oat_file = OatFile::Open(*file.get(), oat_location, NULL);
798 if (oat_file == NULL) {
799 LOG(ERROR) << "Failed to open generated oat file: " << oat_location;
800 return NULL;
801 }
802 class_linker->RegisterOatFile(*oat_file);
803 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
804 if (oat_dex_file == NULL) {
805 LOG(ERROR) << "Failed to find dex file in generated oat file: " << oat_location;
806 return NULL;
807 }
808 return oat_dex_file->OpenDexFile();
809}
810
811const DexFile* ClassLinker::FindDexFileInOatFileFromDexLocation(const std::string& dex_location) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700812 MutexLock mu(dex_lock_);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800813
814 uint32_t dex_location_checksum;
815 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) {
816 LOG(WARNING) << "Failed to compute checksum: " << dex_location;
817 return NULL;
818 }
819
820 const OatFile* open_oat_file = FindOpenedOatFileFromDexLocation(dex_location, dex_location_checksum);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800821 if (open_oat_file != NULL) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800822 return open_oat_file->GetOatDexFile(dex_location)->OpenDexFile();
Brian Carlstromae826982011-11-09 01:33:42 -0800823 }
824
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800825 // Look for an existing file first next to dex and in art-cache
826 std::string oat_filename(OatFile::DexFilenameToOatFilename(dex_location));
827 const OatFile* oat_file(FindOatFileFromOatLocation(oat_filename));
828 if (oat_file != NULL) {
829 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
830 if (dex_location_checksum == oat_dex_file->GetDexFileLocationChecksum()) {
831 return oat_file->GetOatDexFile(dex_location)->OpenDexFile();
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700832 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800833 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
834 << " checksum ( " << std::hex << oat_dex_file->GetDexFileLocationChecksum()
835 << ") mismatch with " << dex_location
836 << " (" << std::hex << dex_location_checksum << ")--- regenerating";
837 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
838 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
Brian Carlstromd601af82012-01-06 10:15:19 -0800839 }
jeffhao262bf462011-10-20 18:36:32 -0700840 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800841 // Try to generate oat file if it wasn't found or was obsolete.
842 std::string oat_cache_filename(GetArtCacheFilenameOrDie(oat_filename));
843 return FindOrCreateOatFileForDexLocation(dex_location, oat_cache_filename);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700844}
845
Brian Carlstromae826982011-11-09 01:33:42 -0800846const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700847 for (size_t i = 0; i < oat_files_.size(); i++) {
848 const OatFile* oat_file = oat_files_[i];
849 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800850 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700851 return oat_file;
852 }
853 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700854 return NULL;
855}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700856
Brian Carlstromae826982011-11-09 01:33:42 -0800857const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
jeffhaof6174e82012-01-31 16:14:17 -0800858 MutexLock mu(dex_lock_);
859 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
860 if (oat_file != NULL) {
861 return oat_file;
862 }
863
864 oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700865 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800866 if (oat_location.empty() || oat_location[0] != '/') {
867 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700868 return NULL;
869 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700870
Brian Carlstroma9f19782011-10-13 00:14:47 -0700871 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Elliott Hughes95572412011-12-13 18:14:20 -0800872 std::string cache_location(GetArtCacheFilenameOrDie(oat_location));
Brian Carlstromae826982011-11-09 01:33:42 -0800873 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700874 if (oat_file != NULL) {
875 return oat_file;
876 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700877 oat_file = OatFile::Open(cache_location, "", NULL);
878 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800879 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700880 return NULL;
881 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700882 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700883
Brian Carlstromae826982011-11-09 01:33:42 -0800884 CHECK(oat_file != NULL) << oat_location;
jeffhaof6174e82012-01-31 16:14:17 -0800885 RegisterOatFileLocked(*oat_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700886 return oat_file;
887}
888
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700889void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800890 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700891 CHECK(!init_done_);
892
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700893 const std::vector<Space*>& spaces = Heap::GetSpaces();
894 for (size_t i = 0; i < spaces.size(); i++) {
Ian Rogers30fab402012-01-23 15:43:46 -0800895 if (spaces[i]->IsImageSpace()) {
896 ImageSpace* space = spaces[i]->AsImageSpace();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700897 OatFile* oat_file = OpenOat(space);
898 CHECK(oat_file != NULL) << "Failed to open oat file for image";
899 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
900 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
901
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800902 if (i == 0) {
903 // Special case of setting up the String class early so that we can test arbitrary objects
904 // as being Strings or not
Ian Rogers30fab402012-01-23 15:43:46 -0800905 Class* java_lang_String = space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800906 ->AsObjectArray<Class>()->Get(kJavaLangString);
907 String::SetClass(java_lang_String);
908 }
909
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700910 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
911 static_cast<uint32_t>(dex_caches->GetLength()));
912 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700913 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800914 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom89521892011-12-07 22:05:07 -0800915 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
916 const DexFile* dex_file = oat_dex_file->OpenDexFile();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700917 if (dex_file == NULL) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800918 LOG(FATAL) << "Failed to open dex file " << dex_file_location
919 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700920 }
921
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800922 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700923
Brian Carlstromdf143242011-10-10 18:05:34 -0700924 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700925 }
926 }
927 }
928
Brian Carlstroma663ea52011-08-19 23:33:41 -0700929 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
930 DCHECK(heap_bitmap != NULL);
931
Brian Carlstroma663ea52011-08-19 23:33:41 -0700932 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700933 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700934
935 // reinit class_roots_
Ian Rogers30fab402012-01-23 15:43:46 -0800936 Object* class_roots_object =
937 spaces[0]->AsImageSpace()->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700938 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700939
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800940 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700941 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
942 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800943 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700944 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700945 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700946 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
947 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
948 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
949 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
950 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
951 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
952 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
953 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700954 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Ian Rogers5167c972012-02-03 10:41:20 -0800955 Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700956 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700957
958 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700959
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800960 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700961}
962
Brian Carlstrom78128a62011-09-15 17:21:19 -0700963void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700964 DCHECK(obj != NULL);
965 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700966 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700967
Elliott Hughesdbb40792011-11-18 17:05:22 -0800968 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700969 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700970 return;
971 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700972 if (obj->IsClass()) {
973 // restore class to ClassLinker::classes_ table
974 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800975 ClassHelper kh(klass, class_linker);
Brian Carlstrom07bb8552012-01-18 22:10:50 -0800976 Class* existing = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
977 DCHECK(existing == NULL) << kh.GetDescriptor();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700978 return;
979 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700980}
981
982// Keep in sync with InitCallback. Anything we visit, we need to
983// reinit references to when reinitializing a ClassLinker from a
984// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700985void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
986 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700987
988 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700989 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700990 }
991
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700992 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700993 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700994 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700995 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700996 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700997 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700998 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700999 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001000
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001001 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001002}
1003
Elliott Hughesa2155262011-11-16 16:26:58 -08001004void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
1005 MutexLock mu(classes_lock_);
1006 typedef Table::const_iterator It; // TODO: C++0x auto
1007 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
1008 if (!visitor(it->second, arg)) {
1009 return;
1010 }
1011 }
1012 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
1013 if (!visitor(it->second, arg)) {
1014 return;
1015 }
1016 }
1017}
1018
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001019ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001020 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001021 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -07001022 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001023 BooleanArray::ResetArrayClass();
1024 ByteArray::ResetArrayClass();
1025 CharArray::ResetArrayClass();
1026 DoubleArray::ResetArrayClass();
1027 FloatArray::ResetArrayClass();
1028 IntArray::ResetArrayClass();
1029 LongArray::ResetArrayClass();
1030 ShortArray::ResetArrayClass();
1031 PathClassLoader::ResetClass();
Ian Rogers5167c972012-02-03 10:41:20 -08001032 Throwable::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001033 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001034 STLDeleteElements(&boot_class_path_);
1035 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001036}
1037
1038DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001039 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
1040 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001041 return NULL;
1042 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001043 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
1044 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001045 return NULL;
1046 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001047 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
1048 if (strings.get() == NULL) {
1049 return NULL;
1050 }
1051 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
1052 if (types.get() == NULL) {
1053 return NULL;
1054 }
1055 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
1056 if (methods.get() == NULL) {
1057 return NULL;
1058 }
1059 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
1060 if (fields.get() == NULL) {
1061 return NULL;
1062 }
1063 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
1064 if (code_and_direct_methods.get() == NULL) {
1065 return NULL;
1066 }
1067 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
1068 if (initialized_static_storage.get() == NULL) {
1069 return NULL;
1070 }
1071
1072 dex_cache->Init(location.get(),
1073 strings.get(),
1074 types.get(),
1075 methods.get(),
1076 fields.get(),
1077 code_and_direct_methods.get(),
1078 initialized_static_storage.get());
1079 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001080}
1081
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001082CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
1083 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -07001084}
1085
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001086InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
1087 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001088 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
1089 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001090 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001091 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001092}
1093
Brian Carlstrom4873d462011-08-21 15:23:39 -07001094Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
1095 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001096 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001097 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001098 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001099 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001100}
1101
Brian Carlstrom4873d462011-08-21 15:23:39 -07001102Class* ClassLinker::AllocClass(size_t class_size) {
1103 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001104}
1105
Jesse Wilson35baaab2011-08-10 16:18:03 -04001106Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001107 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -07001108}
1109
1110Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001111 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001112}
1113
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001114ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
1115 return ObjectArray<StackTraceElement>::Alloc(
1116 GetClassRoot(kJavaLangStackTraceElementArrayClass),
1117 length);
1118}
1119
Brian Carlstromaded5f72011-10-07 17:15:04 -07001120Class* EnsureResolved(Class* klass) {
1121 DCHECK(klass != NULL);
1122 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -07001123 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001124 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001125 ObjectLock lock(klass);
1126 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001127 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001128 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001129 PrettyDescriptor(klass).c_str());
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001130 klass->SetStatus(Class::kStatusError);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001131 return NULL;
1132 }
1133 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001134 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001135 lock.Wait();
1136 }
1137 }
1138 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001139 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001140 return NULL;
1141 }
1142 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001143 CHECK(klass->IsResolved()) << PrettyClass(klass);
1144 CHECK(!self->IsExceptionPending())
1145 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
1146 return klass;
1147}
1148
Elliott Hughesdb7d5e92011-12-16 18:47:37 -08001149Class* ClassLinker::FindSystemClass(const char* descriptor) {
1150 return FindClass(descriptor, NULL);
1151}
1152
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001153Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001154 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001155 Thread* self = Thread::Current();
1156 DCHECK(self != NULL);
1157 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001158 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001159 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1160 // for primitive classes that aren't backed by dex files.
1161 return FindPrimitiveClass(descriptor[0]);
1162 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001163 // Find the class in the loaded classes table.
1164 Class* klass = LookupClass(descriptor, class_loader);
1165 if (klass != NULL) {
1166 return EnsureResolved(klass);
1167 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001168 // Class is not yet loaded.
1169 if (descriptor[0] == '[') {
1170 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001171
Jesse Wilson47daf872011-11-23 11:42:45 -05001172 } else if (class_loader == NULL) {
1173 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1174 if (pair.second != NULL) {
1175 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1176 }
1177
1178 } else if (ClassLoader::UseCompileTimeClassPath()) {
1179 // first try the boot class path
1180 Class* system_class = FindSystemClass(descriptor);
1181 if (system_class != NULL) {
1182 return system_class;
1183 }
1184 CHECK(self->IsExceptionPending());
1185 self->ClearException();
1186
1187 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001188 const std::vector<const DexFile*>& class_path
1189 = ClassLoader::GetCompileTimeClassPath(class_loader);
1190 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001191 if (pair.second != NULL) {
1192 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001193 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001194
1195 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001196 std::string class_name_string(DescriptorToDot(descriptor));
Elliott Hughes09d4d012012-02-03 17:44:20 -08001197 ScopedThreadStateChange tsc(self, Thread::kNative);
Elliott Hughes748382f2012-01-26 18:07:38 -08001198 JNIEnv* env = self->GetJniEnv();
Jesse Wilson47daf872011-11-23 11:42:45 -05001199 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1200 CHECK(c.get() != NULL);
1201 // TODO: cache method?
1202 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1203 CHECK(mid != NULL);
1204 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1205 if (class_name_object.get() == NULL) {
1206 return NULL;
1207 }
1208 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
Ian Rogers761bfa82012-01-11 10:14:05 -08001209 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid,
1210 class_name_object.get()));
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001211 if (env->ExceptionCheck()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001212 // If the ClassLoader threw, pass that exception up.
1213 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001214 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001215 // broken loader - throw NPE to be compatible with Dalvik
1216 ThrowNullPointerException("ClassLoader.loadClass returned null for %s",
1217 class_name_string.c_str());
1218 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001219 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08001220 // success, return Class*
Ian Rogers6b0870d2011-12-15 19:38:12 -08001221 return Decode<Class*>(env, result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001222 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001223 }
1224
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001225 ThrowNoClassDefFoundError("Class %s not found", PrintableString(StringPiece(descriptor)).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001226 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001227}
1228
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001229Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001230 const ClassLoader* class_loader,
1231 const DexFile& dex_file,
1232 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001233 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001234 // Load the class from the dex file.
1235 if (!init_done_) {
1236 // finish up init of hand crafted class_roots_
1237 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001238 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001239 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001240 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001241 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001242 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001243 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001244 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001245 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001246 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001247 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001248 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001249 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001250 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001251 }
1252 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001253 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001254 }
1255 klass->SetDexCache(FindDexCache(dex_file));
1256 LoadClass(dex_file, dex_class_def, klass, class_loader);
1257 // Check for a pending exception during load
1258 Thread* self = Thread::Current();
1259 if (self->IsExceptionPending()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001260 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001261 return NULL;
1262 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001263 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001264 klass->SetClinitThreadId(self->GetTid());
1265 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001266 Class* existing = InsertClass(descriptor, klass.get(), false);
1267 if (existing != NULL) {
1268 // We failed to insert because we raced with another thread.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001269 klass->SetClinitThreadId(0);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001270 klass.reset(existing);
1271 return EnsureResolved(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001272 }
1273 // Finish loading (if necessary) by finding parents
1274 CHECK(!klass->IsLoaded());
1275 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1276 // Loading failed.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001277 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001278 lock.NotifyAll();
1279 return NULL;
1280 }
1281 CHECK(klass->IsLoaded());
1282 // Link the class (if necessary)
1283 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001284 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001285 // Linking failed.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001286 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001287 lock.NotifyAll();
1288 return NULL;
1289 }
1290 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001291
1292 /*
1293 * We send CLASS_PREPARE events to the debugger from here. The
1294 * definition of "preparation" is creating the static fields for a
1295 * class and initializing them to the standard default values, but not
1296 * executing any code (that comes later, during "initialization").
1297 *
1298 * We did the static preparation in LinkClass.
1299 *
1300 * The class has been prepared and resolved but possibly not yet verified
1301 * at this point.
1302 */
1303 Dbg::PostClassPrepare(klass.get());
1304
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001305 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001306}
1307
Brian Carlstrom4873d462011-08-21 15:23:39 -07001308// Precomputes size that will be needed for Class, matching LinkStaticFields
1309size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1310 const DexFile::ClassDef& dex_class_def) {
1311 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001312 size_t num_ref = 0;
1313 size_t num_32 = 0;
1314 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001315 if (class_data != NULL) {
1316 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1317 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001318 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001319 char c = descriptor[0];
1320 if (c == 'L' || c == '[') {
1321 num_ref++;
1322 } else if (c == 'J' || c == 'D') {
1323 num_64++;
1324 } else {
1325 num_32++;
1326 }
1327 }
1328 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001329 // start with generic class data
1330 size_t size = sizeof(Class);
1331 // follow with reference fields which must be contiguous at start
1332 size += (num_ref * sizeof(uint32_t));
1333 // if there are 64-bit fields to add, make sure they are aligned
1334 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1335 if (num_32 != 0) {
1336 // use an available 32-bit field for padding
1337 num_32--;
1338 }
1339 size += sizeof(uint32_t); // either way, we are adding a word
1340 DCHECK_EQ(size, RoundUp(size, 8));
1341 }
1342 // tack on any 64-bit fields now that alignment is assured
1343 size += (num_64 * sizeof(uint64_t));
1344 // tack on any remaining 32-bit fields
1345 size += (num_32 * sizeof(uint32_t));
1346 return size;
1347}
1348
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001349void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001350 // Every kind of method should at least get an invoke stub from the oat_method.
1351 // non-abstract methods also get their code pointers.
1352 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001353 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001354
1355 if (method->IsAbstract()) {
1356 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1357 return;
1358 }
1359 if (method->IsNative()) {
1360 // unregistering restores the dlsym lookup stub
1361 method->UnregisterNative();
jeffhao26c0a1a2012-01-17 16:28:33 -08001362 }
1363
1364 if (Runtime::Current()->IsMethodTracingActive()) {
1365#if defined(__arm__)
1366 Trace* tracer = Runtime::Current()->GetTracer();
1367 void* trace_stub = reinterpret_cast<void*>(art_trace_entry_from_code);
1368 tracer->SaveAndUpdateCode(method.get(), trace_stub);
1369#else
1370 UNIMPLEMENTED(WARNING);
1371#endif
Brian Carlstrom92827a52011-10-10 15:50:01 -07001372 }
1373}
1374
Brian Carlstromf615a612011-07-23 12:50:34 -07001375void ClassLinker::LoadClass(const DexFile& dex_file,
1376 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001377 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001378 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001379 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001380 CHECK(klass->GetDexCache() != NULL);
1381 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001382 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001383 CHECK(descriptor != NULL);
1384
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001385 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001386 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001387 // Make sure that none of our runtime-only flags are set.
1388 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001389 klass->SetAccessFlags(access_flags);
1390 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001391 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001392 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001393
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001394 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001395
Ian Rogers0571d352011-11-03 19:51:38 -07001396 // Load fields fields.
1397 const byte* class_data = dex_file.GetClassData(dex_class_def);
1398 if (class_data == NULL) {
1399 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001400 }
Ian Rogers0571d352011-11-03 19:51:38 -07001401 ClassDataItemIterator it(dex_file, class_data);
1402 if (it.NumStaticFields() != 0) {
1403 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1404 }
1405 if (it.NumInstanceFields() != 0) {
1406 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1407 }
1408 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1409 SirtRef<Field> sfield(AllocField());
1410 klass->SetStaticField(i, sfield.get());
1411 LoadField(dex_file, it, klass, sfield);
1412 }
1413 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1414 SirtRef<Field> ifield(AllocField());
1415 klass->SetInstanceField(i, ifield.get());
1416 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001417 }
1418
Brian Carlstromaded5f72011-10-07 17:15:04 -07001419 UniquePtr<const OatFile::OatClass> oat_class;
1420 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001421 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
1422 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << descriptor;
1423 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1424 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << descriptor;
1425 uint32_t class_def_index;
1426 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1427 CHECK(found) << dex_file.GetLocation() << " " << descriptor;
1428 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
1429 CHECK(oat_class.get() != NULL) << dex_file.GetLocation() << " " << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001430 }
Ian Rogers0571d352011-11-03 19:51:38 -07001431 // Load methods.
1432 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001433 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001434 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001435 }
Ian Rogers0571d352011-11-03 19:51:38 -07001436 if (it.NumVirtualMethods() != 0) {
1437 // TODO: append direct methods to class object
1438 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001439 }
Ian Rogers0571d352011-11-03 19:51:38 -07001440 size_t method_index = 0;
1441 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1442 SirtRef<Method> method(AllocMethod());
1443 klass->SetDirectMethod(i, method.get());
1444 LoadMethod(dex_file, it, klass, method);
1445 if (oat_class.get() != NULL) {
1446 LinkCode(method, oat_class.get(), method_index);
1447 }
1448 method_index++;
1449 }
1450 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1451 SirtRef<Method> method(AllocMethod());
1452 klass->SetVirtualMethod(i, method.get());
1453 LoadMethod(dex_file, it, klass, method);
1454 if (oat_class.get() != NULL) {
1455 LinkCode(method, oat_class.get(), method_index);
1456 }
1457 method_index++;
1458 }
1459 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001460}
1461
Ian Rogers0571d352011-11-03 19:51:38 -07001462void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1463 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001464 uint32_t field_idx = it.GetMemberIndex();
1465 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001466 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001467 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001468}
1469
Ian Rogers0571d352011-11-03 19:51:38 -07001470void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1471 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001472 uint32_t method_idx = it.GetMemberIndex();
1473 dst->SetDexMethodIndex(method_idx);
1474 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001475 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001476
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001477
1478 StringPiece method_name(dex_file.GetMethodName(method_id));
1479 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001480 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1481 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001482
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001483 if (method_name == "finalize") {
1484 // Create the prototype for a signature of "()V"
1485 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1486 if (void_string_id != NULL) {
1487 const DexFile::TypeId* void_type_id =
1488 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1489 if (void_type_id != NULL) {
1490 std::vector<uint16_t> no_args;
1491 const DexFile::ProtoId* finalizer_proto =
1492 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1493 if (finalizer_proto != NULL) {
1494 // We have the prototype in the dex file
1495 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1496 klass->SetFinalizable();
1497 } else {
1498 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1499 // The Enum class declares a "final" finalize() method to prevent subclasses from
1500 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1501 // subclasses, so we exclude it here.
1502 // We also want to avoid setting the flag on Object, where we know that finalize() is
1503 // empty.
1504 if (klass_descriptor != "Ljava/lang/Object;" &&
1505 klass_descriptor != "Ljava/lang/Enum;") {
1506 klass->SetFinalizable();
1507 }
1508 }
1509 }
1510 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001511 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001512 }
Ian Rogers0571d352011-11-03 19:51:38 -07001513 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001514 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001515
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001516 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1517 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1518 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1519 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1520 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1521 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001522}
1523
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001524void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001525 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1526 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001527}
1528
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001529void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1530 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001531 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001532 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001533}
1534
Brian Carlstromaded5f72011-10-07 17:15:04 -07001535bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001536 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001537 for (size_t i = 0; i != dex_files_.size(); ++i) {
1538 if (dex_files_[i] == &dex_file) {
1539 return true;
1540 }
1541 }
1542 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001543}
1544
Brian Carlstromaded5f72011-10-07 17:15:04 -07001545bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001546 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001547 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001548}
1549
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001550void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001551 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001552 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001553 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001554 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001555 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001556}
1557
Brian Carlstromaded5f72011-10-07 17:15:04 -07001558void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001559 {
1560 MutexLock mu(dex_lock_);
1561 if (IsDexFileRegisteredLocked(dex_file)) {
1562 return;
1563 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001564 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001565 // Don't alloc while holding the lock, since allocation may need to
1566 // suspend all threads and another thread may need the dex_lock_ to
1567 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001568 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001569 {
1570 MutexLock mu(dex_lock_);
1571 if (IsDexFileRegisteredLocked(dex_file)) {
1572 return;
1573 }
1574 RegisterDexFileLocked(dex_file, dex_cache);
1575 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001576}
1577
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001578void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001579 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001580 RegisterDexFileLocked(dex_file, dex_cache);
1581}
1582
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001583const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001584 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001585 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001586 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1587 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001588 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001589 }
1590 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001591 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001592 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001593}
1594
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001595DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001596 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001597 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001598 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001599 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001600 }
1601 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001602 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001603 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001604}
1605
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001606Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1607 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001608 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001609 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001610 CHECK(primitive_class != NULL);
1611 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001612 primitive_class->SetPrimitiveType(type);
1613 primitive_class->SetStatus(Class::kStatusInitialized);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001614 Class* existing = InsertClass(descriptor, primitive_class, false);
1615 CHECK(existing == NULL) << "InitPrimitiveClass(" << descriptor << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001616 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001617}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001618
Brian Carlstrombe977852011-07-19 14:54:54 -07001619// Create an array class (i.e. the class object for the array, not the
1620// array itself). "descriptor" looks like "[C" or "[[[[B" or
1621// "[Ljava/lang/String;".
1622//
1623// If "descriptor" refers to an array of primitives, look up the
1624// primitive type's internally-generated class object.
1625//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001626// "class_loader" is the class loader of the class that's referring to
1627// us. It's used to ensure that we're looking for the element type in
1628// the right context. It does NOT become the class loader for the
1629// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001630//
1631// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001632Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001633 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001634
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001635 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001636 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001637 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001638 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001639 return NULL;
1640 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001641
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001642 // See if the component type is already loaded. Array classes are
1643 // always associated with the class loader of their underlying
1644 // element type -- an array of Strings goes with the loader for
1645 // java/lang/String -- so we need to look for it there. (The
1646 // caller should have checked for the existence of the class
1647 // before calling here, but they did so with *their* class loader,
1648 // not the component type's loader.)
1649 //
1650 // If we find it, the caller adds "loader" to the class' initiating
1651 // loader list, which should prevent us from going through this again.
1652 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001653 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001654 // are the same, because our caller (FindClass) just did the
1655 // lookup. (Even if we get this wrong we still have correct behavior,
1656 // because we effectively do this lookup again when we add the new
1657 // class to the hash table --- necessary because of possible races with
1658 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001659 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001660 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001661 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001662 return new_class;
1663 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001664 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001665
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001666 // Fill out the fields in the Class.
1667 //
1668 // It is possible to execute some methods against arrays, because
1669 // all arrays are subclasses of java_lang_Object_, so we need to set
1670 // up a vtable. We can just point at the one in java_lang_Object_.
1671 //
1672 // Array classes are simple enough that we don't need to do a full
1673 // link step.
1674
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001675 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001676 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001677 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001678 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001679 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001680 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001681 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001682 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001683 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001684 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001685 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001686 }
1687 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001688 if (new_class.get() == NULL) {
1689 new_class.reset(AllocClass(sizeof(Class)));
1690 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001691 return NULL;
1692 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001693 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001694 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001695 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001696 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001697 new_class->SetSuperClass(java_lang_Object);
1698 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001699 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001700 new_class->SetClassLoader(component_type->GetClassLoader());
1701 new_class->SetStatus(Class::kStatusInitialized);
1702 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001703 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001704
1705
1706 // All arrays have java/lang/Cloneable and java/io/Serializable as
1707 // interfaces. We need to set that up here, so that stuff like
1708 // "instanceof" works right.
1709 //
1710 // Note: The GC could run during the call to FindSystemClass,
1711 // so we need to make sure the class object is GC-valid while we're in
1712 // there. Do this by clearing the interface list so the GC will just
1713 // think that the entries are null.
1714
1715
1716 // Use the single, global copies of "interfaces" and "iftable"
1717 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001718 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001719 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001720
1721 // Inherit access flags from the component type. Arrays can't be
1722 // used as a superclass or interface, so we want to add "final"
1723 // and remove "interface".
1724 //
1725 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001726 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001727 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001728 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1729 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001730
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001731 Class* existing = InsertClass(descriptor, new_class.get(), false);
1732 if (existing == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001733 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001734 }
1735 // Another thread must have loaded the class after we
1736 // started but before we finished. Abandon what we've
1737 // done.
1738 //
1739 // (Yes, this happens.)
1740
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001741 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001742}
1743
1744Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001745 switch (Primitive::GetType(type)) {
1746 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001747 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001748 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001749 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001750 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001751 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001752 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001753 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001754 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001755 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001756 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001757 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001758 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001759 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001760 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001761 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001762 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001763 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001764 case Primitive::kPrimNot:
1765 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001766 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001767 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001768 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001769 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001770}
1771
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001772Class* ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001773 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001774 DexCache* dex_cache = klass->GetDexCache();
1775 std::string source;
1776 if (dex_cache != NULL) {
1777 source += " from ";
1778 source += dex_cache->GetLocation()->ToModifiedUtf8();
1779 }
1780 LOG(INFO) << "Loaded class " << descriptor << source;
1781 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001782 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001783 MutexLock mu(classes_lock_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001784 Table& classes = image_class ? image_classes_ : classes_;
1785 Class* existing = LookupClass(descriptor.data(), klass->GetClassLoader(), hash, classes);
1786#ifndef NDEBUG
1787 // Check we don't have the class in the other table in error
1788 Table& other_classes = image_class ? classes_ : image_classes_;
1789 CHECK(LookupClass(descriptor.data(), klass->GetClassLoader(), hash, other_classes) == NULL);
1790#endif
1791 if (existing != NULL) {
1792 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07001793 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001794 classes.insert(std::make_pair(hash, klass));
1795 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001796}
1797
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001798bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1799 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001800 MutexLock mu(classes_lock_);
Elliott Hughese5448b52012-01-18 16:44:06 -08001801 typedef Table::iterator It; // TODO: C++0x auto
Brian Carlstromae826982011-11-09 01:33:42 -08001802 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001803 ClassHelper kh;
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001804 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001805 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001806 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001807 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001808 classes_.erase(it);
1809 return true;
1810 }
1811 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001812 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001813 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001814 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001815 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001816 image_classes_.erase(it);
1817 return true;
1818 }
1819 }
1820 return false;
1821}
1822
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001823Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1824 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001825 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001826 // TODO: determine if its better to search classes_ or image_classes_ first
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001827 Class* klass = LookupClass(descriptor, class_loader, hash, classes_);
1828 if (klass != NULL) {
1829 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001830 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001831 return LookupClass(descriptor, class_loader, hash, image_classes_);
1832}
1833
1834Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader,
1835 size_t hash, const Table& classes) {
1836 ClassHelper kh(NULL, this);
1837 typedef Table::const_iterator It; // TODO: C++0x auto
1838 for (It it = classes.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001839 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001840 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001841 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001842#ifndef NDEBUG
1843 for (++it; it != end && it->first == hash; ++it) {
Ian Rogersd85016c2012-02-03 18:27:34 -08001844 Class* klass2 = it->second;
1845 kh.ChangeClass(klass2);
1846 CHECK(!(strcmp(descriptor, kh.GetDescriptor()) == 0 && klass2->GetClassLoader() == class_loader))
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001847 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
Ian Rogersd85016c2012-02-03 18:27:34 -08001848 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001849 }
1850#endif
Ian Rogers5d76c432011-10-31 21:42:49 -07001851 return klass;
1852 }
1853 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001854 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001855}
1856
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001857void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001858 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001859 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001860 MutexLock mu(classes_lock_);
1861 typedef Table::const_iterator It; // TODO: C++0x auto
1862 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001863 ClassHelper kh(NULL, this);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001864 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001865 Class* klass = it->second;
1866 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001867 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001868 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001869 }
1870 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001871 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001872 Class* klass = it->second;
1873 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001874 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001875 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001876 }
1877 }
1878}
1879
Ian Rogersc20a83e2012-01-18 18:15:32 -08001880#ifndef NDEBUG
1881static void CheckMethodsHaveGcMaps(Class* klass) {
1882 if (!Runtime::Current()->IsStarted()) {
1883 return;
1884 }
1885 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
1886 Method* method = klass->GetDirectMethod(i);
1887 if (!method->IsNative() && !method->IsAbstract()) {
1888 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1889 }
1890 }
1891 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
1892 Method* method = klass->GetVirtualMethod(i);
1893 if (!method->IsNative() && !method->IsAbstract()) {
1894 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1895 }
1896 }
1897}
1898#else
1899static void CheckMethodsHaveGcMaps(Class* klass) {
1900}
1901#endif
1902
jeffhao98eacac2011-09-14 16:11:53 -07001903void ClassLinker::VerifyClass(Class* klass) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001904 ObjectLock lock(klass);
1905
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001906 // TODO: assert that the monitor on the Class is held
jeffhao98eacac2011-09-14 16:11:53 -07001907 if (klass->IsVerified()) {
1908 return;
1909 }
1910
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001911 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved) << PrettyClass(klass);
jeffhao98eacac2011-09-14 16:11:53 -07001912 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001913
Ian Rogers1c5eb702012-02-01 09:18:34 -08001914 // Verify super class
1915 Class* super = klass->GetSuperClass();
1916 std::string error_msg;
1917 if (super != NULL) {
1918 // Acquire lock to prevent races on verifying the super class
1919 ObjectLock lock(super);
1920
1921 if (!super->IsVerified() && !super->IsErroneous()) {
1922 Runtime::Current()->GetClassLinker()->VerifyClass(super);
1923 }
1924 if (!super->IsVerified()) {
1925 error_msg = "Rejecting class ";
1926 error_msg += PrettyDescriptor(klass);
1927 error_msg += " that attempts to sub-class erroneous class ";
1928 error_msg += PrettyDescriptor(super);
1929 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
1930 Thread* self = Thread::Current();
1931 SirtRef<Throwable> cause(self->GetException());
1932 if (cause.get() != NULL) {
1933 self->ClearException();
1934 }
1935 self->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
1936 if (cause.get() != NULL) {
1937 self->GetException()->SetCause(cause.get());
1938 }
1939 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyDescriptor(klass);
1940 klass->SetStatus(Class::kStatusError);
1941 return;
1942 }
1943 }
1944
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001945 // Try to use verification information from oat file, otherwise do runtime verification
1946 const DexFile& dex_file = FindDexFile(klass->GetDexCache());
Ian Rogers1c5eb702012-02-01 09:18:34 -08001947 if (VerifyClassUsingOatFile(dex_file, klass) ||
1948 verifier::DexVerifier::VerifyClass(klass, error_msg)) {
Ian Rogersc4762272012-02-01 15:55:55 -08001949 DCHECK(!Thread::Current()->IsExceptionPending());
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001950 // Make sure all classes referenced by catch blocks are resolved
1951 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001952 klass->SetStatus(Class::kStatusVerified);
Ian Rogersc20a83e2012-01-18 18:15:32 -08001953 // Sanity check that a verified class has GC maps on all methods
1954 CheckMethodsHaveGcMaps(klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001955 } else {
Ian Rogers09f6b562012-01-31 21:58:52 -08001956 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass)
Ian Rogers1c5eb702012-02-01 09:18:34 -08001957 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
1958 << " because: " << error_msg;
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001959 Thread* self = Thread::Current();
Ian Rogersc4762272012-02-01 15:55:55 -08001960 CHECK(!self->IsExceptionPending());
Ian Rogers1c5eb702012-02-01 09:18:34 -08001961 self->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
1962 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyDescriptor(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001963 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001964 }
jeffhao98eacac2011-09-14 16:11:53 -07001965}
1966
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001967bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, Class* klass) {
1968 if (!Runtime::Current()->IsStarted()) {
1969 return false;
1970 }
1971 if (ClassLoader::UseCompileTimeClassPath()) {
1972 return false;
1973 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001974 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
1975 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001976 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001977 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001978 const char* descriptor = ClassHelper(klass).GetDescriptor();
1979 uint32_t class_def_index;
1980 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001981 CHECK(found) << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001982 UniquePtr<const OatFile::OatClass> oat_class(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001983 CHECK(oat_class.get() != NULL)
1984 << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001985 Class::Status status = oat_class->GetStatus();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001986 if (status == Class::kStatusVerified || status == Class::kStatusInitialized) {
1987 return true;
1988 }
Ian Rogersc4762272012-02-01 15:55:55 -08001989 if (status == Class::kStatusError) {
1990 // Compile time verification failed. Compile time verification can fail because we have
1991 // incomplete type information. Consider the following:
1992 // class ... {
1993 // Foo x;
1994 // .... () {
1995 // if (...) {
1996 // v1 gets assigned a type of resolved class Foo
1997 // } else {
1998 // v1 gets assigned a type of unresolved class Bar
1999 // }
2000 // iput x = v1
2001 // } }
2002 // when we merge v1 following the if-the-else it results in Conflict
2003 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
2004 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
2005 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
2006 // at compile time).
2007 return false;
2008 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002009 if (status == Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08002010 // Status is uninitialized if we couldn't determine the status at compile time, for example,
2011 // not loading the class.
2012 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
2013 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002014 return false;
2015 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002016 LOG(FATAL) << "Unexpected class status: " << status
2017 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
2018
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002019 return false;
2020}
2021
2022void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, Class* klass) {
2023 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
2024 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
2025 }
2026 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
2027 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
2028 }
2029}
2030
2031void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, Method* method) {
2032 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
2033 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
2034 if (code_item == NULL) {
2035 return; // native or abstract method
2036 }
2037 if (code_item->tries_size_ == 0) {
2038 return; // nothing to process
2039 }
2040 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
2041 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2042 ClassLinker* linker = Runtime::Current()->GetClassLinker();
2043 for (uint32_t idx = 0; idx < handlers_size; idx++) {
2044 CatchHandlerIterator iterator(handlers_ptr);
2045 for (; iterator.HasNext(); iterator.Next()) {
2046 // Ensure exception types are resolved so that they don't need resolution to be delivered,
2047 // unresolved exception types will be ignored by exception delivery
2048 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
2049 Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
2050 if (exception_type == NULL) {
2051 DCHECK(Thread::Current()->IsExceptionPending());
2052 Thread::Current()->ClearException();
2053 }
2054 }
2055 }
2056 handlers_ptr = iterator.EndDataPointer();
2057 }
2058}
2059
Ian Rogersc2b44472011-12-14 21:17:17 -08002060static void CheckProxyConstructor(Method* constructor);
2061static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
2062
Jesse Wilson95caa792011-10-12 18:14:17 -04002063Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002064 ClassLoader* loader, ObjectArray<Method>* methods,
2065 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08002066 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002067 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08002068 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04002069 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002070 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002071 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002072 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002073 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07002074 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002075 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08002076
2077 klass->SetStatus(Class::kStatusIdx);
2078
2079 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
2080
2081 // Create static field that holds throws, instance fields are inherited
2082 klass->SetSFields(AllocObjectArray<Field>(1));
2083 SirtRef<Field> sfield(AllocField());
2084 klass->SetStaticField(0, sfield.get());
2085 sfield->SetDexFieldIndex(-1);
2086 sfield->SetDeclaringClass(klass.get());
2087 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002088
Ian Rogers466bb252011-10-14 03:29:56 -07002089 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04002090 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002091 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04002092
Ian Rogers466bb252011-10-14 03:29:56 -07002093 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04002094 size_t num_virtual_methods = methods->GetLength();
2095 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
2096 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002097 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002098 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04002099 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002100
2101 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
2102 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
2103 DCHECK(!Thread::Current()->IsExceptionPending());
2104
2105 // Link the fields and virtual methods, creating vtable and iftables
2106 if (!LinkClass(klass, interfaces)) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002107 klass->SetStatus(Class::kStatusError);
Jesse Wilson95caa792011-10-12 18:14:17 -04002108 return NULL;
2109 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002110 sfield->SetObject(NULL, throws); // initialize throws field
2111 klass->SetStatus(Class::kStatusInitialized);
2112
2113 // sanity checks
2114#ifndef NDEBUG
2115 bool debug = true;
2116#else
2117 bool debug = false;
2118#endif
2119 if (debug) {
2120 CHECK(klass->GetIFields() == NULL);
2121 CheckProxyConstructor(klass->GetDirectMethod(0));
2122 for (size_t i = 0; i < num_virtual_methods; ++i) {
2123 SirtRef<Method> prototype(methods->Get(i));
2124 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
2125 }
Brian Carlstrom89521892011-12-07 22:05:07 -08002126 std::string throws_field_name("java.lang.Class[][] ");
Ian Rogersc2b44472011-12-14 21:17:17 -08002127 throws_field_name += name->ToModifiedUtf8();
2128 throws_field_name += ".throws";
2129 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
2130
2131 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
2132 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
2133 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002134 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04002135}
2136
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002137std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
2138 DCHECK(proxy_class->IsProxyClass());
2139 String* name = proxy_class->GetName();
2140 DCHECK(name != NULL);
2141 return DotToDescriptor(name->ToModifiedUtf8().c_str());
2142}
2143
2144
2145Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07002146 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07002147 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04002148 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07002149 Method* proxy_constructor = proxy_direct_methods->Get(2);
2150 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
2151 // code_ too)
2152 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
2153 // Make this constructor public and fix the class to be our Proxy version
2154 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002155 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08002156 return constructor;
2157}
2158
2159static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07002160 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002161 MethodHelper mh(constructor);
2162 CHECK_STREQ(mh.GetName(), "<init>");
Elliott Hughesba8eee12012-01-24 20:25:24 -08002163 CHECK_EQ(mh.GetSignature(), std::string("(Ljava/lang/reflect/InvocationHandler;)V"));
Ian Rogers466bb252011-10-14 03:29:56 -07002164 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04002165}
2166
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002167Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
2168 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
2169 // prototype method
2170 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
2171 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07002172 // as necessary
2173 Method* method = down_cast<Method*>(prototype->Clone());
2174
2175 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
2176 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002177 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07002178 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002179
Ian Rogers466bb252011-10-14 03:29:56 -07002180 // At runtime the method looks like a reference and argument saving method, clone the code
2181 // related parameters from this method.
2182 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
2183 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
2184 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
2185 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
2186 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08002187 return method;
2188}
Jesse Wilson95caa792011-10-12 18:14:17 -04002189
Ian Rogersc2b44472011-12-14 21:17:17 -08002190static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07002191 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002192 CHECK(!prototype->IsFinal());
2193 CHECK(method->IsFinal());
2194 CHECK(!method->IsAbstract());
2195 MethodHelper mh(method);
2196 const char* method_name = mh.GetName();
2197 const char* method_shorty = mh.GetShorty();
2198 Class* method_return = mh.GetReturnType();
2199
2200 mh.ChangeMethod(prototype.get());
2201
2202 CHECK_STREQ(mh.GetName(), method_name);
2203 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07002204
2205 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002206 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04002207}
2208
Brian Carlstrom25c33252011-09-18 15:58:35 -07002209bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002210 CHECK(klass->IsResolved() || klass->IsErroneous())
2211 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002212
Carl Shapirob5573532011-07-12 18:22:59 -07002213 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002214
Brian Carlstrom25c33252011-09-18 15:58:35 -07002215 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002216 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002217 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002218 ObjectLock lock(klass);
2219
Brian Carlstromd1422f82011-09-28 11:37:09 -07002220 if (klass->GetStatus() == Class::kStatusInitialized) {
2221 return true;
2222 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002223
Brian Carlstromd1422f82011-09-28 11:37:09 -07002224 if (klass->IsErroneous()) {
2225 ThrowEarlierClassFailure(klass);
2226 return false;
2227 }
2228
2229 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07002230 VerifyClass(klass);
2231 if (klass->GetStatus() != Class::kStatusVerified) {
Ian Rogers595799e2012-01-11 17:32:51 -08002232 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002233 return false;
2234 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002235 }
2236
Brian Carlstrom25c33252011-09-18 15:58:35 -07002237 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
2238 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002239 // if the class has a <clinit> but we can't run it during compilation,
Ian Rogers595799e2012-01-11 17:32:51 -08002240 // don't bother going to kStatusInitializing. We return true to maintain
2241 // the invariant that a false result implies there is a pending exception.
2242 return true;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002243 }
2244
Brian Carlstromd1422f82011-09-28 11:37:09 -07002245 // If the class is kStatusInitializing, either this thread is
2246 // initializing higher up the stack or another thread has beat us
2247 // to initializing and we need to wait. Either way, this
2248 // invocation of InitializeClass will not be responsible for
2249 // running <clinit> and will return.
2250 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002251 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002252 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002253 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002254 return true;
2255 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002256 // No. That's fine. Wait for another thread to finish initializing.
2257 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002258 }
2259
2260 if (!ValidateSuperClassDescriptors(klass)) {
2261 klass->SetStatus(Class::kStatusError);
2262 return false;
2263 }
2264
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002265 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified) << PrettyClass(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002266
Elliott Hughesdcc24742011-09-07 14:02:44 -07002267 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002268 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002269 }
2270
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002271 uint64_t t0 = NanoTime();
2272
Brian Carlstrom25c33252011-09-18 15:58:35 -07002273 if (!InitializeSuperClass(klass, can_run_clinit)) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002274 CHECK(klass->IsErroneous());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002275 return false;
2276 }
2277
2278 InitializeStaticFields(klass);
2279
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002280 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002281 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002282 }
2283
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002284 uint64_t t1 = NanoTime();
2285
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002286 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002287 {
2288 ObjectLock lock(klass);
2289
2290 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002291 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002292 klass->SetStatus(Class::kStatusError);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002293 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002294 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002295 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2296 RuntimeStats* thread_stats = self->GetStats();
2297 ++global_stats->class_init_count;
2298 ++thread_stats->class_init_count;
2299 global_stats->class_init_time_ns += (t1 - t0);
2300 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002301 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002302 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002303 ClassHelper kh(klass);
2304 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002305 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002306 }
2307 lock.NotifyAll();
2308 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002309 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002310}
2311
Brian Carlstromd1422f82011-09-28 11:37:09 -07002312bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
2313 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002314 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002315 lock.Wait();
2316
2317 // When we wake up, repeat the test for init-in-progress. If
2318 // there's an exception pending (only possible if
2319 // "interruptShouldThrow" was set), bail out.
2320 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002321 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002322 klass->SetStatus(Class::kStatusError);
2323 return false;
2324 }
2325 // Spurious wakeup? Go back to waiting.
2326 if (klass->GetStatus() == Class::kStatusInitializing) {
2327 continue;
2328 }
2329 if (klass->IsErroneous()) {
2330 // The caller wants an exception, but it was thrown in a
2331 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002332 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002333 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002334 return false;
2335 }
2336 if (klass->IsInitialized()) {
2337 return true;
2338 }
2339 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2340 }
2341 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2342}
2343
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002344bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2345 if (klass->IsInterface()) {
2346 return true;
2347 }
2348 // begin with the methods local to the superclass
2349 if (klass->HasSuperClass() &&
2350 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2351 const Class* super = klass->GetSuperClass();
Ian Rogers595799e2012-01-11 17:32:51 -08002352 for (int i = super->GetVTable()->GetLength() - 1; i >= 0; --i) {
2353 const Method* method = klass->GetVTable()->Get(i);
2354 if (method != super->GetVTable()->Get(i) &&
2355 !IsSameMethodSignatureInDifferentClassContexts(method, super, klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002356 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2357 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2358 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002359 return false;
2360 }
2361 }
2362 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002363 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2364 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2365 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002366 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2367 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002368 const Method* method = interface_entry->GetMethodArray()->Get(j);
Ian Rogers595799e2012-01-11 17:32:51 -08002369 if (!IsSameMethodSignatureInDifferentClassContexts(method, interface,
2370 method->GetDeclaringClass())) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002371 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2372 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2373 PrettyMethod(method).c_str(),
2374 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002375 return false;
2376 }
2377 }
2378 }
2379 }
2380 return true;
2381}
2382
Ian Rogers595799e2012-01-11 17:32:51 -08002383// Returns true if classes referenced by the signature of the method are the
2384// same classes in klass1 as they are in klass2.
2385bool ClassLinker::IsSameMethodSignatureInDifferentClassContexts(const Method* method,
2386 const Class* klass1,
2387 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002388 if (klass1 == klass2) {
2389 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002390 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002391 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002392 const DexFile::ProtoId& proto_id =
2393 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002394 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2395 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002396 if (descriptor == NULL) {
2397 break;
2398 }
2399 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2400 // Found a non-primitive type.
Ian Rogers595799e2012-01-11 17:32:51 -08002401 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002402 return false;
2403 }
2404 }
2405 }
2406 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002407 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002408 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Ian Rogers595799e2012-01-11 17:32:51 -08002409 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002410 return false;
2411 }
2412 }
2413 return true;
2414}
2415
Ian Rogers595799e2012-01-11 17:32:51 -08002416// Returns true if the descriptor resolves to the same class in the context of klass1 and klass2.
2417bool ClassLinker::IsSameDescriptorInDifferentClassContexts(const char* descriptor,
2418 const Class* klass1,
2419 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002420 CHECK(descriptor != NULL);
2421 CHECK(klass1 != NULL);
2422 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002423 if (klass1 == klass2) {
2424 return true;
2425 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002426 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Ian Rogers595799e2012-01-11 17:32:51 -08002427 if (found1 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002428 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002429 }
Ian Rogers595799e2012-01-11 17:32:51 -08002430 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
2431 if (found2 == NULL) {
2432 Thread::Current()->ClearException();
2433 }
2434 return found1 == found2;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002435}
2436
Brian Carlstrom25c33252011-09-18 15:58:35 -07002437bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002438 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002439 if (!klass->IsInterface() && klass->HasSuperClass()) {
2440 Class* super_class = klass->GetSuperClass();
2441 if (super_class->GetStatus() != Class::kStatusInitialized) {
2442 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002443 Thread* self = Thread::Current();
2444 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002445 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002446 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002447 // TODO: check for a pending exception
2448 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002449 if (!can_run_clinit) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002450 // Don't set status to error when we can't run <clinit>.
2451 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing) << PrettyClass(klass);
2452 klass->SetStatus(Class::kStatusVerified);
2453 return false;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002454 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002455 klass->SetStatus(Class::kStatusError);
2456 klass->NotifyAll();
2457 return false;
2458 }
2459 }
2460 }
2461 return true;
2462}
2463
Brian Carlstrom25c33252011-09-18 15:58:35 -07002464bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002465 CHECK(c != NULL);
2466 if (c->IsInitialized()) {
2467 return true;
2468 }
2469
Elliott Hughes5f791332011-09-15 17:45:30 -07002470 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002471 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Ian Rogers595799e2012-01-11 17:32:51 -08002472 bool success = InitializeClass(c, can_run_clinit);
2473 if (!success) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002474 CHECK(self->IsExceptionPending()) << PrettyClass(c);
Ian Rogers595799e2012-01-11 17:32:51 -08002475 }
2476 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002477}
2478
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002479void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002480 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002481 const ClassLoader* cl = c->GetClassLoader();
2482 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002483 ClassDataItemIterator it(dex_file, class_data);
2484 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2485 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002486 }
2487}
2488
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002489void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002490 size_t num_static_fields = klass->NumStaticFields();
2491 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002492 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002493 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002494 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002495 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002496 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002497 return;
2498 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002499 ClassHelper kh(klass);
2500 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002501 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002502 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002503 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002504
Ian Rogers0571d352011-11-03 19:51:38 -07002505 if (it.HasNext()) {
2506 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2507 std::map<uint32_t, Field*> field_map;
2508 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2509 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2510 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002511 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002512 }
2513}
2514
Ian Rogersc2b44472011-12-14 21:17:17 -08002515bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002516 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002517 if (!LinkSuperClass(klass)) {
2518 return false;
2519 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002520 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002521 return false;
2522 }
2523 if (!LinkInstanceFields(klass)) {
2524 return false;
2525 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002526 if (!LinkStaticFields(klass)) {
2527 return false;
2528 }
2529 CreateReferenceInstanceOffsets(klass);
2530 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002531 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2532 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002533 return true;
2534}
2535
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002536bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002537 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002538 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2539 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
Ian Rogerscab01012012-01-10 17:35:46 -08002540 CHECK(class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002541 uint16_t super_class_idx = class_def->superclass_idx_;
2542 if (super_class_idx != DexFile::kDexNoIndex16) {
2543 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002544 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002545 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002546 return false;
2547 }
Ian Rogersbe125a92012-01-11 15:19:49 -08002548 // Verify
2549 if (!klass->CanAccess(super_class)) {
2550 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2551 "Class %s extended by class %s is inaccessible",
2552 PrettyDescriptor(super_class).c_str(),
2553 PrettyDescriptor(klass.get()).c_str());
2554 return false;
2555 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002556 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002557 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002558 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2559 if (interfaces != NULL) {
2560 for (size_t i = 0; i < interfaces->Size(); i++) {
2561 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2562 Class* interface = ResolveType(dex_file, idx, klass.get());
2563 if (interface == NULL) {
2564 DCHECK(Thread::Current()->IsExceptionPending());
2565 return false;
2566 }
2567 // Verify
2568 if (!klass->CanAccess(interface)) {
2569 // TODO: the RI seemed to ignore this in my testing.
2570 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2571 "Interface %s implemented by class %s is inaccessible",
2572 PrettyDescriptor(interface).c_str(),
2573 PrettyDescriptor(klass.get()).c_str());
2574 return false;
2575 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002576 }
2577 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002578 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002579 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002580 return true;
2581}
2582
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002583bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002584 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002585 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002586 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002587 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002588 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002589 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002590 return false;
2591 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002592 return true;
2593 }
2594 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002595 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002596 return false;
2597 }
2598 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002599 if (super->IsFinal() || super->IsInterface()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002600 Thread* self = Thread::Current();
2601 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002602 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002603 PrettyDescriptor(super).c_str(),
2604 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002605 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002606 return false;
2607 }
2608 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002609 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002610 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002611 PrettyDescriptor(super).c_str(),
2612 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002613 return false;
2614 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002615
2616 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2617 if (super->IsFinalizable()) {
2618 klass->SetFinalizable();
2619 }
2620
Elliott Hughes2da50362011-10-10 16:57:08 -07002621 // Inherit reference flags (if any) from the superclass.
2622 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2623 if (reference_flags != 0) {
2624 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2625 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002626 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002627 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002628 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002629 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002630 return false;
2631 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002632
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002633#ifndef NDEBUG
2634 // Ensure super classes are fully resolved prior to resolving fields..
2635 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002636 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002637 super = super->GetSuperClass();
2638 }
2639#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002640 return true;
2641}
2642
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002643// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002644bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002645 if (klass->IsInterface()) {
2646 // No vtable.
2647 size_t count = klass->NumVirtualMethods();
2648 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002649 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002650 return false;
2651 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002652 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002653 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002654 }
jeffhaobdb76512011-09-07 11:43:16 -07002655 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002656 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002657 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002658 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002659 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002660 }
2661 return true;
2662}
2663
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002664bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002665 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002666 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2667 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002668 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002669 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002670 SirtRef<ObjectArray<Method> > vtable(klass->GetSuperClass()->GetVTable()->CopyOf(max_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002671 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002672 MethodHelper local_mh(NULL, this);
2673 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002674 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002675 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002676 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002677 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002678 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002679 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002680 super_mh.ChangeMethod(super_method);
2681 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002682 // Verify
2683 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002684 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002685 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002686 PrettyDescriptor(klass.get()).c_str(),
2687 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002688 return false;
2689 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002690 vtable->Set(j, local_method);
2691 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002692 break;
2693 }
2694 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002695 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002696 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002697 vtable->Set(actual_count, local_method);
2698 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002699 actual_count += 1;
2700 }
2701 }
2702 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002703 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002704 return false;
2705 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002706 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002707 CHECK_LE(actual_count, max_count);
2708 if (actual_count < max_count) {
Ian Rogers30fab402012-01-23 15:43:46 -08002709 vtable.reset(vtable->CopyOf(actual_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002710 }
Ian Rogers30fab402012-01-23 15:43:46 -08002711 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002712 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002713 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002714 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002715 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002716 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002717 return false;
2718 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002719 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002720 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002721 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2722 vtable->Set(i, virtual_method);
2723 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002724 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002725 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002726 }
2727 return true;
2728}
2729
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002730bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002731 size_t super_ifcount;
2732 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002733 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002734 } else {
2735 super_ifcount = 0;
2736 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002737 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002738 ClassHelper kh(klass.get(), this);
2739 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2740 ifcount += num_interfaces;
2741 for (size_t i = 0; i < num_interfaces; i++) {
2742 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2743 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002744 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002745 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002746 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002747 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002748 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002749 return true;
2750 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002751 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002752 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002753 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2754 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogersb52b01a2012-01-12 17:01:38 -08002755 Class* super_interface = super_iftable->Get(i)->GetInterface();
2756 iftable->Set(i, AllocInterfaceEntry(super_interface));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002757 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002758 }
2759 // Flatten the interface inheritance hierarchy.
2760 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002761 for (size_t i = 0; i < num_interfaces; i++) {
2762 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002763 DCHECK(interface != NULL);
2764 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002765 ClassHelper ih(interface);
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002766 Thread* self = Thread::Current();
2767 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002768 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002769 PrettyDescriptor(klass.get()).c_str(),
2770 PrettyDescriptor(ih.GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002771 return false;
2772 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002773 // Check if interface is already in iftable
2774 bool duplicate = false;
2775 for (size_t j = 0; j < idx; j++) {
2776 Class* existing_interface = iftable->Get(j)->GetInterface();
2777 if (existing_interface == interface) {
2778 duplicate = true;
2779 break;
2780 }
2781 }
2782 if (!duplicate) {
2783 // Add this non-duplicate interface.
2784 iftable->Set(idx++, AllocInterfaceEntry(interface));
2785 // Add this interface's non-duplicate super-interfaces.
2786 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2787 Class* super_interface = interface->GetIfTable()->Get(j)->GetInterface();
2788 bool super_duplicate = false;
2789 for (size_t k = 0; k < idx; k++) {
2790 Class* existing_interface = iftable->Get(k)->GetInterface();
2791 if (existing_interface == super_interface) {
2792 super_duplicate = true;
2793 break;
2794 }
2795 }
2796 if (!super_duplicate) {
2797 iftable->Set(idx++, AllocInterfaceEntry(super_interface));
2798 }
2799 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002800 }
2801 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002802 // Shrink iftable in case duplicates were found
2803 if (idx < ifcount) {
2804 iftable.reset(iftable->CopyOf(idx));
2805 ifcount = idx;
2806 } else {
2807 CHECK_EQ(idx, ifcount);
2808 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002809 klass->SetIfTable(iftable.get());
Elliott Hughes4681c802011-09-25 18:04:37 -07002810
2811 // If we're an interface, we don't need the vtable pointers, so we're done.
2812 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002813 return true;
2814 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002815 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002816 MethodHelper vtable_mh(NULL, this);
2817 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002818 for (size_t i = 0; i < ifcount; ++i) {
2819 InterfaceEntry* interface_entry = iftable->Get(i);
2820 Class* interface = interface_entry->GetInterface();
2821 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2822 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002823 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002824 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2825 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002826 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002827 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002828 // For each method listed in the interface's method list, find the
2829 // matching method in our class's method list. We want to favor the
2830 // subclass over the superclass, which just requires walking
2831 // back from the end of the vtable. (This only matters if the
2832 // superclass defines a private method and this class redefines
2833 // it -- otherwise it would use the same vtable slot. In .dex files
2834 // those don't end up in the virtual method table, so it shouldn't
2835 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002836 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2837 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002838 vtable_mh.ChangeMethod(vtable_method);
2839 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002840 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002841 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002842 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002843 return false;
2844 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002845 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002846 break;
2847 }
2848 }
2849 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002850 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002851 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002852 Method* mir_method = miranda_list[mir];
2853 vtable_mh.ChangeMethod(mir_method);
2854 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002855 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002856 break;
2857 }
2858 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002859 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002860 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002861 miranda_method.reset(AllocMethod());
2862 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2863 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002864 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002865 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002866 }
2867 }
2868 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002869 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002870 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002871 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002872 klass->SetVirtualMethods((old_method_count == 0)
2873 ? AllocObjectArray<Method>(new_method_count)
2874 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002875
Ian Rogers30fab402012-01-23 15:43:46 -08002876 SirtRef<ObjectArray<Method> > vtable(klass->GetVTableDuringLinking());
2877 CHECK(vtable.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002878 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002879 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers30fab402012-01-23 15:43:46 -08002880 vtable.reset(vtable->CopyOf(new_vtable_count));
Elliott Hughes4681c802011-09-25 18:04:37 -07002881 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002882 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002883 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002884 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2885 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2886 klass->SetVirtualMethod(old_method_count + i, method);
2887 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002888 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002889 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002890 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002891 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002892
2893 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2894 for (int i = 0; i < vtable->GetLength(); ++i) {
2895 CHECK(vtable->Get(i) != NULL);
2896 }
2897
2898// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2899
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002900 return true;
2901}
2902
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002903bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2904 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002905 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002906}
2907
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002908bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2909 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002910 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002911 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002912 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002913 return success;
2914}
2915
Brian Carlstromdbc05252011-09-09 01:59:59 -07002916struct LinkFieldsComparator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002917 explicit LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002918 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002919 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002920 fh_->ChangeField(field1);
2921 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2922 fh_->ChangeField(field2);
2923 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002924 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2925 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2926 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2927 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002928 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2929 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2930 if (order1 != order2) {
2931 return order1 < order2;
2932 }
2933
2934 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002935 fh_->ChangeField(field1);
2936 StringPiece name1(fh_->GetName());
2937 fh_->ChangeField(field2);
2938 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002939 return name1 < name2;
2940 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002941
2942 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002943};
2944
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002945bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002946 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002947 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002948
2949 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002950 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002951
2952 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002953 size_t size;
2954 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002955 if (is_static) {
2956 size = klass->GetClassSize();
2957 field_offset = Class::FieldsOffset();
2958 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002959 Class* super_class = klass->GetSuperClass();
2960 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002961 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002962 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002963 }
2964 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002965 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002966
Brian Carlstromdbc05252011-09-09 01:59:59 -07002967 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002968
Brian Carlstromdbc05252011-09-09 01:59:59 -07002969 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002970 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002971 std::deque<Field*> grouped_and_sorted_fields;
2972 for (size_t i = 0; i < num_fields; i++) {
2973 grouped_and_sorted_fields.push_back(fields->Get(i));
2974 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002975 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002976 std::sort(grouped_and_sorted_fields.begin(),
2977 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002978 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002979
2980 // References should be at the front.
2981 size_t current_field = 0;
2982 size_t num_reference_fields = 0;
2983 for (; current_field < num_fields; current_field++) {
2984 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002985 fh.ChangeField(field);
2986 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002987 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002988 if (isPrimitive) {
2989 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002990 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002991 grouped_and_sorted_fields.pop_front();
2992 num_reference_fields++;
2993 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002994 field->SetOffset(field_offset);
2995 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002996 }
2997
2998 // Now we want to pack all of the double-wide fields together. If
2999 // we're not aligned, though, we want to shuffle one 32-bit field
3000 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07003001 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003002 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
3003 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003004 fh.ChangeField(field);
3005 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003006 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
3007 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003008 continue;
3009 }
3010 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003011 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003012 // drop the consumed field
3013 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
3014 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003015 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07003016 // whether we found a 32-bit field for padding or not, we advance
3017 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003018 }
3019
3020 // Alignment is good, shuffle any double-wide fields forward, and
3021 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07003022 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07003023 while (!grouped_and_sorted_fields.empty()) {
3024 Field* field = grouped_and_sorted_fields.front();
3025 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003026 fh.ChangeField(field);
3027 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003028 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07003029 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003030 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003031 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003032 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07003033 ? sizeof(uint64_t)
3034 : sizeof(uint32_t)));
3035 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003036 }
3037
Elliott Hughesadb460d2011-10-05 17:02:34 -07003038 // 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 -08003039 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
3040 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07003041 // We know there are no non-reference fields in the Reference classes, and we know
3042 // that 'referent' is alphabetically last, so this is easy...
3043 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003044 fh.ChangeField(fields->Get(num_fields - 1));
Elliott Hughesba8eee12012-01-24 20:25:24 -08003045 CHECK_STREQ(fh.GetName(), "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07003046 --num_reference_fields;
3047 }
3048
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003049#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07003050 // Make sure that all reference fields appear before
3051 // non-reference fields, and all double-wide fields are aligned.
3052 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07003053 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003054 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003055 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003056 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003057 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07003058 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07003059 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
3060 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003061 fh.ChangeField(field);
3062 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003063 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003064 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07003065 is_primitive = true; // We lied above, so we have to expect a lie here.
3066 }
3067 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07003068 if (!seen_non_ref) {
3069 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003070 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003071 }
Brian Carlstrombe977852011-07-19 14:54:54 -07003072 } else {
3073 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003074 }
3075 }
Brian Carlstrombe977852011-07-19 14:54:54 -07003076 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003077 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003078 }
3079#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003080 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003081 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003082 if (is_static) {
3083 klass->SetNumReferenceStaticFields(num_reference_fields);
3084 klass->SetClassSize(size);
3085 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003086 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003087 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003088 klass->SetObjectSize(size);
3089 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003090 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003091 return true;
3092}
3093
3094// Set the bitmap of reference offsets, refOffsets, from the ifields
3095// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003096void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003097 uint32_t reference_offsets = 0;
3098 Class* super_class = klass->GetSuperClass();
3099 if (super_class != NULL) {
3100 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003101 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003102 if (reference_offsets == CLASS_WALK_SUPER) {
3103 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003104 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003105 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003106 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003107 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003108}
3109
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003110void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003111 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003112}
3113
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003114void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003115 uint32_t reference_offsets) {
3116 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003117 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
3118 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003119 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003120 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003121 // All of the fields that contain object references are guaranteed
3122 // to be at the beginning of the fields list.
3123 for (size_t i = 0; i < num_reference_fields; ++i) {
3124 // Note that byte_offset is the offset from the beginning of
3125 // object, not the offset into instance data
3126 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003127 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003128 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
3129 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
3130 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07003131 CHECK_NE(new_bit, 0U);
3132 reference_offsets |= new_bit;
3133 } else {
3134 reference_offsets = CLASS_WALK_SUPER;
3135 break;
3136 }
3137 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003138 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003139 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003140 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003141 } else {
3142 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003143 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003144}
3145
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003146String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07003147 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003148 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003149 if (resolved != NULL) {
3150 return resolved;
3151 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003152 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
3153 int32_t utf16_length = dex_file.GetStringLength(string_id);
3154 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07003155 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003156 dex_cache->SetResolvedString(string_idx, string);
3157 return string;
3158}
3159
3160Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003161 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003162 DexCache* dex_cache,
3163 const ClassLoader* class_loader) {
3164 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003165 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07003166 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003167 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003168 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05003169 // TODO: we used to throw here if resolved's class loader was not the
3170 // boot class loader. This was to permit different classes with the
3171 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003172 dex_cache->SetResolvedType(type_idx, resolved);
3173 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08003174 CHECK(Thread::Current()->IsExceptionPending())
3175 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003176 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003177 }
3178 return resolved;
3179}
3180
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003181Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
3182 uint32_t method_idx,
3183 DexCache* dex_cache,
3184 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003185 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003186 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
3187 if (resolved != NULL) {
3188 return resolved;
3189 }
3190 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3191 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
3192 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07003193 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003194 return NULL;
3195 }
3196
Ian Rogers0571d352011-11-03 19:51:38 -07003197 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
3198 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003199 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003200 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003201 } else if (klass->IsInterface()) {
3202 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003203 } else {
3204 resolved = klass->FindVirtualMethod(name, signature);
3205 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003206 if (resolved != NULL) {
3207 dex_cache->SetResolvedMethod(method_idx, resolved);
3208 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003209 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003210 }
3211 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003212}
3213
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003214Field* ClassLinker::ResolveField(const DexFile& dex_file,
3215 uint32_t field_idx,
3216 DexCache* dex_cache,
3217 const ClassLoader* class_loader,
3218 bool is_static) {
3219 Field* resolved = dex_cache->GetResolvedField(field_idx);
3220 if (resolved != NULL) {
3221 return resolved;
3222 }
3223 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3224 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3225 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003226 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003227 return NULL;
3228 }
3229
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003230 const char* name = dex_file.GetFieldName(field_id);
3231 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003232 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003233 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003234 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003235 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003236 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003237 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003238 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003239 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08003240 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
3241 }
3242 return resolved;
3243}
3244
3245Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
3246 uint32_t field_idx,
3247 DexCache* dex_cache,
3248 const ClassLoader* class_loader) {
3249 Field* resolved = dex_cache->GetResolvedField(field_idx);
3250 if (resolved != NULL) {
3251 return resolved;
3252 }
3253 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3254 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3255 if (klass == NULL) {
3256 DCHECK(Thread::Current()->IsExceptionPending());
3257 return NULL;
3258 }
3259
3260 const char* name = dex_file.GetFieldName(field_id);
3261 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3262 resolved = klass->FindField(name, type);
3263 if (resolved != NULL) {
3264 dex_cache->SetResolvedField(field_idx, resolved);
3265 } else {
3266 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003267 }
3268 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07003269}
3270
Ian Rogersad25ac52011-10-04 19:13:33 -07003271const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
3272 Class* declaring_class = referrer->GetDeclaringClass();
3273 DexCache* dex_cache = declaring_class->GetDexCache();
3274 const DexFile& dex_file = FindDexFile(dex_cache);
3275 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3276 return dex_file.GetShorty(method_id.proto_idx_);
3277}
3278
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003279void ClassLinker::DumpAllClasses(int flags) const {
3280 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3281 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3282 std::vector<Class*> all_classes;
3283 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003284 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003285 typedef Table::const_iterator It; // TODO: C++0x auto
3286 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3287 all_classes.push_back(it->second);
3288 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003289 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3290 all_classes.push_back(it->second);
3291 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003292 }
3293
3294 for (size_t i = 0; i < all_classes.size(); ++i) {
3295 all_classes[i]->DumpClass(std::cerr, flags);
3296 }
3297}
3298
Elliott Hughescac6cc72011-11-03 20:31:21 -07003299void ClassLinker::DumpForSigQuit(std::ostream& os) const {
3300 MutexLock mu(classes_lock_);
3301 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3302 << classes_.size() << " allocated classes\n";
3303}
3304
Elliott Hughese27955c2011-08-26 15:21:24 -07003305size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003306 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003307 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003308}
3309
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003310pid_t ClassLinker::GetClassesLockOwner() {
3311 return classes_lock_.GetOwner();
3312}
3313
3314pid_t ClassLinker::GetDexLockOwner() {
3315 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003316}
3317
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003318void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3319 DCHECK(!init_done_);
3320
3321 DCHECK(klass != NULL);
3322 DCHECK(klass->GetClassLoader() == NULL);
3323
3324 DCHECK(class_roots_ != NULL);
3325 DCHECK(class_roots_->Get(class_root) == NULL);
3326 class_roots_->Set(class_root, klass);
3327}
3328
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003329} // namespace art