blob: 62d3df787f63f84c793d60aa05259e74f42fc5bf [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);
Elliott Hughescd1410a2012-02-13 16:06:39 -08001389 // Set ACC_SUPER; dex files don't contain this flag, but all classes are supposed to have it set.
1390 access_flags |= kAccSuper;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001391 klass->SetAccessFlags(access_flags);
1392 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001393 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001394 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001395
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001396 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001397
Ian Rogers0571d352011-11-03 19:51:38 -07001398 // Load fields fields.
1399 const byte* class_data = dex_file.GetClassData(dex_class_def);
1400 if (class_data == NULL) {
1401 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001402 }
Ian Rogers0571d352011-11-03 19:51:38 -07001403 ClassDataItemIterator it(dex_file, class_data);
1404 if (it.NumStaticFields() != 0) {
1405 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1406 }
1407 if (it.NumInstanceFields() != 0) {
1408 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1409 }
1410 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1411 SirtRef<Field> sfield(AllocField());
1412 klass->SetStaticField(i, sfield.get());
1413 LoadField(dex_file, it, klass, sfield);
1414 }
1415 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1416 SirtRef<Field> ifield(AllocField());
1417 klass->SetInstanceField(i, ifield.get());
1418 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001419 }
1420
Brian Carlstromaded5f72011-10-07 17:15:04 -07001421 UniquePtr<const OatFile::OatClass> oat_class;
1422 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001423 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
1424 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << descriptor;
1425 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1426 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << descriptor;
1427 uint32_t class_def_index;
1428 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1429 CHECK(found) << dex_file.GetLocation() << " " << descriptor;
1430 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
1431 CHECK(oat_class.get() != NULL) << dex_file.GetLocation() << " " << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001432 }
Ian Rogers0571d352011-11-03 19:51:38 -07001433 // Load methods.
1434 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001435 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001436 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001437 }
Ian Rogers0571d352011-11-03 19:51:38 -07001438 if (it.NumVirtualMethods() != 0) {
1439 // TODO: append direct methods to class object
1440 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001441 }
Ian Rogers0571d352011-11-03 19:51:38 -07001442 size_t method_index = 0;
1443 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1444 SirtRef<Method> method(AllocMethod());
1445 klass->SetDirectMethod(i, method.get());
1446 LoadMethod(dex_file, it, klass, method);
1447 if (oat_class.get() != NULL) {
1448 LinkCode(method, oat_class.get(), method_index);
1449 }
1450 method_index++;
1451 }
1452 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1453 SirtRef<Method> method(AllocMethod());
1454 klass->SetVirtualMethod(i, method.get());
1455 LoadMethod(dex_file, it, klass, method);
1456 if (oat_class.get() != NULL) {
1457 LinkCode(method, oat_class.get(), method_index);
1458 }
1459 method_index++;
1460 }
1461 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001462}
1463
Ian Rogers0571d352011-11-03 19:51:38 -07001464void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1465 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001466 uint32_t field_idx = it.GetMemberIndex();
1467 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001468 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001469 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001470}
1471
Ian Rogers0571d352011-11-03 19:51:38 -07001472void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1473 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001474 uint32_t method_idx = it.GetMemberIndex();
1475 dst->SetDexMethodIndex(method_idx);
1476 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001477 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001478
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001479
1480 StringPiece method_name(dex_file.GetMethodName(method_id));
1481 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001482 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1483 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001484
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001485 if (method_name == "finalize") {
1486 // Create the prototype for a signature of "()V"
1487 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1488 if (void_string_id != NULL) {
1489 const DexFile::TypeId* void_type_id =
1490 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1491 if (void_type_id != NULL) {
1492 std::vector<uint16_t> no_args;
1493 const DexFile::ProtoId* finalizer_proto =
1494 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1495 if (finalizer_proto != NULL) {
1496 // We have the prototype in the dex file
1497 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1498 klass->SetFinalizable();
1499 } else {
1500 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1501 // The Enum class declares a "final" finalize() method to prevent subclasses from
1502 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1503 // subclasses, so we exclude it here.
1504 // We also want to avoid setting the flag on Object, where we know that finalize() is
1505 // empty.
1506 if (klass_descriptor != "Ljava/lang/Object;" &&
1507 klass_descriptor != "Ljava/lang/Enum;") {
1508 klass->SetFinalizable();
1509 }
1510 }
1511 }
1512 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001513 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001514 }
Ian Rogers0571d352011-11-03 19:51:38 -07001515 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001516 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001517
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001518 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1519 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Ian Rogersb5d6a492012-02-14 04:00:51 -08001520 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001521 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1522 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001523}
1524
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001525void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001526 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1527 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001528}
1529
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001530void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1531 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001532 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001533 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001534}
1535
Brian Carlstromaded5f72011-10-07 17:15:04 -07001536bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001537 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001538 for (size_t i = 0; i != dex_files_.size(); ++i) {
1539 if (dex_files_[i] == &dex_file) {
1540 return true;
1541 }
1542 }
1543 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001544}
1545
Brian Carlstromaded5f72011-10-07 17:15:04 -07001546bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001547 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001548 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001549}
1550
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001551void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001552 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001553 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001554 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001555 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001556 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001557}
1558
Brian Carlstromaded5f72011-10-07 17:15:04 -07001559void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001560 {
1561 MutexLock mu(dex_lock_);
1562 if (IsDexFileRegisteredLocked(dex_file)) {
1563 return;
1564 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001565 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001566 // Don't alloc while holding the lock, since allocation may need to
1567 // suspend all threads and another thread may need the dex_lock_ to
1568 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001569 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001570 {
1571 MutexLock mu(dex_lock_);
1572 if (IsDexFileRegisteredLocked(dex_file)) {
1573 return;
1574 }
1575 RegisterDexFileLocked(dex_file, dex_cache);
1576 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001577}
1578
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001579void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001580 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001581 RegisterDexFileLocked(dex_file, dex_cache);
1582}
1583
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001584const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001585 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001586 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001587 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1588 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001589 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001590 }
1591 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001592 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001593 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001594}
1595
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001596DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001597 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001598 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001599 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001600 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001601 }
1602 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001603 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001604 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001605}
1606
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001607Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1608 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001609 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001610 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001611 CHECK(primitive_class != NULL);
1612 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001613 primitive_class->SetPrimitiveType(type);
1614 primitive_class->SetStatus(Class::kStatusInitialized);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001615 Class* existing = InsertClass(descriptor, primitive_class, false);
1616 CHECK(existing == NULL) << "InitPrimitiveClass(" << descriptor << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001617 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001618}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001619
Brian Carlstrombe977852011-07-19 14:54:54 -07001620// Create an array class (i.e. the class object for the array, not the
1621// array itself). "descriptor" looks like "[C" or "[[[[B" or
1622// "[Ljava/lang/String;".
1623//
1624// If "descriptor" refers to an array of primitives, look up the
1625// primitive type's internally-generated class object.
1626//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001627// "class_loader" is the class loader of the class that's referring to
1628// us. It's used to ensure that we're looking for the element type in
1629// the right context. It does NOT become the class loader for the
1630// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001631//
1632// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001633Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001634 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001635
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001636 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001637 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001638 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001639 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001640 return NULL;
1641 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001642
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001643 // See if the component type is already loaded. Array classes are
1644 // always associated with the class loader of their underlying
1645 // element type -- an array of Strings goes with the loader for
1646 // java/lang/String -- so we need to look for it there. (The
1647 // caller should have checked for the existence of the class
1648 // before calling here, but they did so with *their* class loader,
1649 // not the component type's loader.)
1650 //
1651 // If we find it, the caller adds "loader" to the class' initiating
1652 // loader list, which should prevent us from going through this again.
1653 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001654 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001655 // are the same, because our caller (FindClass) just did the
1656 // lookup. (Even if we get this wrong we still have correct behavior,
1657 // because we effectively do this lookup again when we add the new
1658 // class to the hash table --- necessary because of possible races with
1659 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001660 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001661 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001662 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001663 return new_class;
1664 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001665 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001666
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001667 // Fill out the fields in the Class.
1668 //
1669 // It is possible to execute some methods against arrays, because
1670 // all arrays are subclasses of java_lang_Object_, so we need to set
1671 // up a vtable. We can just point at the one in java_lang_Object_.
1672 //
1673 // Array classes are simple enough that we don't need to do a full
1674 // link step.
1675
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001676 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001677 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001678 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001679 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001680 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001681 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001682 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001683 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001684 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001685 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001686 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001687 }
1688 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001689 if (new_class.get() == NULL) {
1690 new_class.reset(AllocClass(sizeof(Class)));
1691 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001692 return NULL;
1693 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001694 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001695 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001696 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001697 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001698 new_class->SetSuperClass(java_lang_Object);
1699 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001700 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001701 new_class->SetClassLoader(component_type->GetClassLoader());
1702 new_class->SetStatus(Class::kStatusInitialized);
1703 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001704 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001705
1706
1707 // All arrays have java/lang/Cloneable and java/io/Serializable as
1708 // interfaces. We need to set that up here, so that stuff like
1709 // "instanceof" works right.
1710 //
1711 // Note: The GC could run during the call to FindSystemClass,
1712 // so we need to make sure the class object is GC-valid while we're in
1713 // there. Do this by clearing the interface list so the GC will just
1714 // think that the entries are null.
1715
1716
1717 // Use the single, global copies of "interfaces" and "iftable"
1718 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001719 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001720 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001721
1722 // Inherit access flags from the component type. Arrays can't be
1723 // used as a superclass or interface, so we want to add "final"
1724 // and remove "interface".
1725 //
1726 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001727 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001728 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001729 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1730 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001731
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001732 Class* existing = InsertClass(descriptor, new_class.get(), false);
1733 if (existing == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001734 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001735 }
1736 // Another thread must have loaded the class after we
1737 // started but before we finished. Abandon what we've
1738 // done.
1739 //
1740 // (Yes, this happens.)
1741
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001742 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001743}
1744
1745Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001746 switch (Primitive::GetType(type)) {
1747 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001748 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001749 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001750 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001751 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001752 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001753 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001754 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001755 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001756 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001757 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001758 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001759 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001760 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001761 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001762 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001763 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001764 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001765 case Primitive::kPrimNot:
1766 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001767 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001768 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001769 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001770 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001771}
1772
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001773Class* ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001774 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001775 DexCache* dex_cache = klass->GetDexCache();
1776 std::string source;
1777 if (dex_cache != NULL) {
1778 source += " from ";
1779 source += dex_cache->GetLocation()->ToModifiedUtf8();
1780 }
1781 LOG(INFO) << "Loaded class " << descriptor << source;
1782 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001783 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001784 MutexLock mu(classes_lock_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001785 Table& classes = image_class ? image_classes_ : classes_;
1786 Class* existing = LookupClass(descriptor.data(), klass->GetClassLoader(), hash, classes);
1787#ifndef NDEBUG
1788 // Check we don't have the class in the other table in error
1789 Table& other_classes = image_class ? classes_ : image_classes_;
1790 CHECK(LookupClass(descriptor.data(), klass->GetClassLoader(), hash, other_classes) == NULL);
1791#endif
1792 if (existing != NULL) {
1793 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07001794 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001795 classes.insert(std::make_pair(hash, klass));
1796 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001797}
1798
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001799bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1800 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001801 MutexLock mu(classes_lock_);
Elliott Hughese5448b52012-01-18 16:44:06 -08001802 typedef Table::iterator It; // TODO: C++0x auto
Brian Carlstromae826982011-11-09 01:33:42 -08001803 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001804 ClassHelper kh;
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001805 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001806 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001807 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001808 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001809 classes_.erase(it);
1810 return true;
1811 }
1812 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001813 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001814 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001815 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001816 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001817 image_classes_.erase(it);
1818 return true;
1819 }
1820 }
1821 return false;
1822}
1823
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001824Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1825 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001826 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001827 // TODO: determine if its better to search classes_ or image_classes_ first
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001828 Class* klass = LookupClass(descriptor, class_loader, hash, classes_);
1829 if (klass != NULL) {
1830 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001831 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001832 return LookupClass(descriptor, class_loader, hash, image_classes_);
1833}
1834
1835Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader,
1836 size_t hash, const Table& classes) {
1837 ClassHelper kh(NULL, this);
1838 typedef Table::const_iterator It; // TODO: C++0x auto
1839 for (It it = classes.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001840 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001841 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001842 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001843#ifndef NDEBUG
1844 for (++it; it != end && it->first == hash; ++it) {
Ian Rogersd85016c2012-02-03 18:27:34 -08001845 Class* klass2 = it->second;
1846 kh.ChangeClass(klass2);
1847 CHECK(!(strcmp(descriptor, kh.GetDescriptor()) == 0 && klass2->GetClassLoader() == class_loader))
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001848 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
Ian Rogersd85016c2012-02-03 18:27:34 -08001849 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001850 }
1851#endif
Ian Rogers5d76c432011-10-31 21:42:49 -07001852 return klass;
1853 }
1854 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001855 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001856}
1857
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001858void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001859 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001860 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001861 MutexLock mu(classes_lock_);
1862 typedef Table::const_iterator It; // TODO: C++0x auto
1863 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001864 ClassHelper kh(NULL, this);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001865 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001866 Class* klass = it->second;
1867 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001868 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001869 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001870 }
1871 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001872 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001873 Class* klass = it->second;
1874 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001875 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001876 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001877 }
1878 }
1879}
1880
Ian Rogersc20a83e2012-01-18 18:15:32 -08001881#ifndef NDEBUG
1882static void CheckMethodsHaveGcMaps(Class* klass) {
1883 if (!Runtime::Current()->IsStarted()) {
1884 return;
1885 }
1886 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
1887 Method* method = klass->GetDirectMethod(i);
1888 if (!method->IsNative() && !method->IsAbstract()) {
1889 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1890 }
1891 }
1892 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
1893 Method* method = klass->GetVirtualMethod(i);
1894 if (!method->IsNative() && !method->IsAbstract()) {
1895 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1896 }
1897 }
1898}
1899#else
1900static void CheckMethodsHaveGcMaps(Class* klass) {
1901}
1902#endif
1903
jeffhao98eacac2011-09-14 16:11:53 -07001904void ClassLinker::VerifyClass(Class* klass) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001905 ObjectLock lock(klass);
1906
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001907 // TODO: assert that the monitor on the Class is held
jeffhao98eacac2011-09-14 16:11:53 -07001908 if (klass->IsVerified()) {
1909 return;
1910 }
1911
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001912 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved) << PrettyClass(klass);
jeffhao98eacac2011-09-14 16:11:53 -07001913 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001914
Ian Rogers1c5eb702012-02-01 09:18:34 -08001915 // Verify super class
1916 Class* super = klass->GetSuperClass();
1917 std::string error_msg;
1918 if (super != NULL) {
1919 // Acquire lock to prevent races on verifying the super class
1920 ObjectLock lock(super);
1921
1922 if (!super->IsVerified() && !super->IsErroneous()) {
1923 Runtime::Current()->GetClassLinker()->VerifyClass(super);
1924 }
1925 if (!super->IsVerified()) {
1926 error_msg = "Rejecting class ";
1927 error_msg += PrettyDescriptor(klass);
1928 error_msg += " that attempts to sub-class erroneous class ";
1929 error_msg += PrettyDescriptor(super);
1930 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
1931 Thread* self = Thread::Current();
1932 SirtRef<Throwable> cause(self->GetException());
1933 if (cause.get() != NULL) {
1934 self->ClearException();
1935 }
1936 self->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
1937 if (cause.get() != NULL) {
1938 self->GetException()->SetCause(cause.get());
1939 }
1940 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyDescriptor(klass);
1941 klass->SetStatus(Class::kStatusError);
1942 return;
1943 }
1944 }
1945
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001946 // Try to use verification information from oat file, otherwise do runtime verification
1947 const DexFile& dex_file = FindDexFile(klass->GetDexCache());
Ian Rogers1c5eb702012-02-01 09:18:34 -08001948 if (VerifyClassUsingOatFile(dex_file, klass) ||
1949 verifier::DexVerifier::VerifyClass(klass, error_msg)) {
Ian Rogersc4762272012-02-01 15:55:55 -08001950 DCHECK(!Thread::Current()->IsExceptionPending());
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001951 // Make sure all classes referenced by catch blocks are resolved
1952 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001953 klass->SetStatus(Class::kStatusVerified);
Ian Rogersc20a83e2012-01-18 18:15:32 -08001954 // Sanity check that a verified class has GC maps on all methods
1955 CheckMethodsHaveGcMaps(klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001956 } else {
Ian Rogers09f6b562012-01-31 21:58:52 -08001957 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass)
Ian Rogers1c5eb702012-02-01 09:18:34 -08001958 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
1959 << " because: " << error_msg;
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001960 Thread* self = Thread::Current();
Ian Rogersc4762272012-02-01 15:55:55 -08001961 CHECK(!self->IsExceptionPending());
Ian Rogers1c5eb702012-02-01 09:18:34 -08001962 self->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
1963 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyDescriptor(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001964 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001965 }
jeffhao98eacac2011-09-14 16:11:53 -07001966}
1967
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001968bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, Class* klass) {
1969 if (!Runtime::Current()->IsStarted()) {
1970 return false;
1971 }
1972 if (ClassLoader::UseCompileTimeClassPath()) {
1973 return false;
1974 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001975 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
1976 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001977 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001978 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001979 const char* descriptor = ClassHelper(klass).GetDescriptor();
1980 uint32_t class_def_index;
1981 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001982 CHECK(found) << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001983 UniquePtr<const OatFile::OatClass> oat_class(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001984 CHECK(oat_class.get() != NULL)
1985 << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001986 Class::Status status = oat_class->GetStatus();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001987 if (status == Class::kStatusVerified || status == Class::kStatusInitialized) {
1988 return true;
1989 }
Ian Rogersc4762272012-02-01 15:55:55 -08001990 if (status == Class::kStatusError) {
1991 // Compile time verification failed. Compile time verification can fail because we have
1992 // incomplete type information. Consider the following:
1993 // class ... {
1994 // Foo x;
1995 // .... () {
1996 // if (...) {
1997 // v1 gets assigned a type of resolved class Foo
1998 // } else {
1999 // v1 gets assigned a type of unresolved class Bar
2000 // }
2001 // iput x = v1
2002 // } }
2003 // when we merge v1 following the if-the-else it results in Conflict
2004 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
2005 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
2006 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
2007 // at compile time).
2008 return false;
2009 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002010 if (status == Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08002011 // Status is uninitialized if we couldn't determine the status at compile time, for example,
2012 // not loading the class.
2013 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
2014 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002015 return false;
2016 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002017 LOG(FATAL) << "Unexpected class status: " << status
2018 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
2019
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002020 return false;
2021}
2022
2023void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, Class* klass) {
2024 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
2025 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
2026 }
2027 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
2028 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
2029 }
2030}
2031
2032void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, Method* method) {
2033 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
2034 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
2035 if (code_item == NULL) {
2036 return; // native or abstract method
2037 }
2038 if (code_item->tries_size_ == 0) {
2039 return; // nothing to process
2040 }
2041 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
2042 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2043 ClassLinker* linker = Runtime::Current()->GetClassLinker();
2044 for (uint32_t idx = 0; idx < handlers_size; idx++) {
2045 CatchHandlerIterator iterator(handlers_ptr);
2046 for (; iterator.HasNext(); iterator.Next()) {
2047 // Ensure exception types are resolved so that they don't need resolution to be delivered,
2048 // unresolved exception types will be ignored by exception delivery
2049 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
2050 Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
2051 if (exception_type == NULL) {
2052 DCHECK(Thread::Current()->IsExceptionPending());
2053 Thread::Current()->ClearException();
2054 }
2055 }
2056 }
2057 handlers_ptr = iterator.EndDataPointer();
2058 }
2059}
2060
Ian Rogersc2b44472011-12-14 21:17:17 -08002061static void CheckProxyConstructor(Method* constructor);
2062static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
2063
Jesse Wilson95caa792011-10-12 18:14:17 -04002064Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002065 ClassLoader* loader, ObjectArray<Method>* methods,
2066 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08002067 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002068 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08002069 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04002070 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002071 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002072 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002073 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002074 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07002075 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002076 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08002077
2078 klass->SetStatus(Class::kStatusIdx);
2079
2080 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
2081
2082 // Create static field that holds throws, instance fields are inherited
2083 klass->SetSFields(AllocObjectArray<Field>(1));
2084 SirtRef<Field> sfield(AllocField());
2085 klass->SetStaticField(0, sfield.get());
2086 sfield->SetDexFieldIndex(-1);
2087 sfield->SetDeclaringClass(klass.get());
2088 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002089
Ian Rogers466bb252011-10-14 03:29:56 -07002090 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04002091 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002092 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04002093
Ian Rogers466bb252011-10-14 03:29:56 -07002094 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04002095 size_t num_virtual_methods = methods->GetLength();
2096 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
2097 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002098 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002099 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04002100 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002101
2102 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
2103 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
2104 DCHECK(!Thread::Current()->IsExceptionPending());
2105
2106 // Link the fields and virtual methods, creating vtable and iftables
2107 if (!LinkClass(klass, interfaces)) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002108 klass->SetStatus(Class::kStatusError);
Jesse Wilson95caa792011-10-12 18:14:17 -04002109 return NULL;
2110 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002111 sfield->SetObject(NULL, throws); // initialize throws field
2112 klass->SetStatus(Class::kStatusInitialized);
2113
2114 // sanity checks
2115#ifndef NDEBUG
2116 bool debug = true;
2117#else
2118 bool debug = false;
2119#endif
2120 if (debug) {
2121 CHECK(klass->GetIFields() == NULL);
2122 CheckProxyConstructor(klass->GetDirectMethod(0));
2123 for (size_t i = 0; i < num_virtual_methods; ++i) {
2124 SirtRef<Method> prototype(methods->Get(i));
2125 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
2126 }
Brian Carlstrom89521892011-12-07 22:05:07 -08002127 std::string throws_field_name("java.lang.Class[][] ");
Ian Rogersc2b44472011-12-14 21:17:17 -08002128 throws_field_name += name->ToModifiedUtf8();
2129 throws_field_name += ".throws";
2130 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
2131
2132 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
2133 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
2134 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002135 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04002136}
2137
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002138std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
2139 DCHECK(proxy_class->IsProxyClass());
2140 String* name = proxy_class->GetName();
2141 DCHECK(name != NULL);
2142 return DotToDescriptor(name->ToModifiedUtf8().c_str());
2143}
2144
2145
2146Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07002147 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07002148 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04002149 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07002150 Method* proxy_constructor = proxy_direct_methods->Get(2);
2151 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
2152 // code_ too)
2153 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
2154 // Make this constructor public and fix the class to be our Proxy version
2155 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002156 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08002157 return constructor;
2158}
2159
2160static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07002161 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002162 MethodHelper mh(constructor);
2163 CHECK_STREQ(mh.GetName(), "<init>");
Elliott Hughesba8eee12012-01-24 20:25:24 -08002164 CHECK_EQ(mh.GetSignature(), std::string("(Ljava/lang/reflect/InvocationHandler;)V"));
Ian Rogers466bb252011-10-14 03:29:56 -07002165 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04002166}
2167
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002168Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
2169 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
2170 // prototype method
Ian Rogersb5d6a492012-02-14 04:00:51 -08002171 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002172 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07002173 // as necessary
2174 Method* method = down_cast<Method*>(prototype->Clone());
2175
2176 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
2177 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002178 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07002179 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002180
Ian Rogers466bb252011-10-14 03:29:56 -07002181 // At runtime the method looks like a reference and argument saving method, clone the code
2182 // related parameters from this method.
2183 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
2184 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
2185 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
2186 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
2187 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08002188 return method;
2189}
Jesse Wilson95caa792011-10-12 18:14:17 -04002190
Ian Rogersc2b44472011-12-14 21:17:17 -08002191static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07002192 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002193 CHECK(!prototype->IsFinal());
2194 CHECK(method->IsFinal());
2195 CHECK(!method->IsAbstract());
2196 MethodHelper mh(method);
2197 const char* method_name = mh.GetName();
2198 const char* method_shorty = mh.GetShorty();
2199 Class* method_return = mh.GetReturnType();
2200
2201 mh.ChangeMethod(prototype.get());
2202
2203 CHECK_STREQ(mh.GetName(), method_name);
2204 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07002205
2206 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002207 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04002208}
2209
Brian Carlstrom25c33252011-09-18 15:58:35 -07002210bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002211 CHECK(klass->IsResolved() || klass->IsErroneous())
2212 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002213
Carl Shapirob5573532011-07-12 18:22:59 -07002214 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002215
Brian Carlstrom25c33252011-09-18 15:58:35 -07002216 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002217 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002218 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002219 ObjectLock lock(klass);
2220
Brian Carlstromd1422f82011-09-28 11:37:09 -07002221 if (klass->GetStatus() == Class::kStatusInitialized) {
2222 return true;
2223 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002224
Brian Carlstromd1422f82011-09-28 11:37:09 -07002225 if (klass->IsErroneous()) {
2226 ThrowEarlierClassFailure(klass);
2227 return false;
2228 }
2229
2230 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07002231 VerifyClass(klass);
2232 if (klass->GetStatus() != Class::kStatusVerified) {
Ian Rogers595799e2012-01-11 17:32:51 -08002233 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002234 return false;
2235 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002236 }
2237
Brian Carlstrom25c33252011-09-18 15:58:35 -07002238 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
2239 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002240 // if the class has a <clinit> but we can't run it during compilation,
Ian Rogers1bddec32012-02-04 12:27:34 -08002241 // don't bother going to kStatusInitializing. We return false so that
2242 // sub-classes don't believe this class is initialized.
2243 return false;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002244 }
2245
Brian Carlstromd1422f82011-09-28 11:37:09 -07002246 // If the class is kStatusInitializing, either this thread is
2247 // initializing higher up the stack or another thread has beat us
2248 // to initializing and we need to wait. Either way, this
2249 // invocation of InitializeClass will not be responsible for
2250 // running <clinit> and will return.
2251 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002252 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002253 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002254 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002255 return true;
2256 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002257 // No. That's fine. Wait for another thread to finish initializing.
2258 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002259 }
2260
2261 if (!ValidateSuperClassDescriptors(klass)) {
2262 klass->SetStatus(Class::kStatusError);
2263 return false;
2264 }
2265
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002266 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified) << PrettyClass(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002267
Elliott Hughesdcc24742011-09-07 14:02:44 -07002268 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002269 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002270 }
2271
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002272 uint64_t t0 = NanoTime();
2273
Brian Carlstrom25c33252011-09-18 15:58:35 -07002274 if (!InitializeSuperClass(klass, can_run_clinit)) {
Ian Rogers1bddec32012-02-04 12:27:34 -08002275 // Super class initialization failed, this can be because we can't run
2276 // super-class class initializers in which case we'll be verified.
2277 // Otherwise this class is erroneous.
2278 if (!can_run_clinit) {
2279 CHECK(klass->IsVerified());
2280 } else {
2281 CHECK(klass->IsErroneous());
2282 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002283 return false;
2284 }
2285
2286 InitializeStaticFields(klass);
2287
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002288 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002289 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002290 }
2291
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002292 uint64_t t1 = NanoTime();
2293
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002294 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002295 {
2296 ObjectLock lock(klass);
2297
2298 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002299 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002300 klass->SetStatus(Class::kStatusError);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002301 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002302 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002303 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2304 RuntimeStats* thread_stats = self->GetStats();
2305 ++global_stats->class_init_count;
2306 ++thread_stats->class_init_count;
2307 global_stats->class_init_time_ns += (t1 - t0);
2308 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002309 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002310 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002311 ClassHelper kh(klass);
2312 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002313 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002314 }
2315 lock.NotifyAll();
2316 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002317 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002318}
2319
Brian Carlstromd1422f82011-09-28 11:37:09 -07002320bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
2321 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002322 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002323 lock.Wait();
2324
2325 // When we wake up, repeat the test for init-in-progress. If
2326 // there's an exception pending (only possible if
2327 // "interruptShouldThrow" was set), bail out.
2328 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002329 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002330 klass->SetStatus(Class::kStatusError);
2331 return false;
2332 }
2333 // Spurious wakeup? Go back to waiting.
2334 if (klass->GetStatus() == Class::kStatusInitializing) {
2335 continue;
2336 }
2337 if (klass->IsErroneous()) {
2338 // The caller wants an exception, but it was thrown in a
2339 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002340 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002341 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002342 return false;
2343 }
2344 if (klass->IsInitialized()) {
2345 return true;
2346 }
2347 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2348 }
2349 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2350}
2351
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002352bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2353 if (klass->IsInterface()) {
2354 return true;
2355 }
2356 // begin with the methods local to the superclass
2357 if (klass->HasSuperClass() &&
2358 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2359 const Class* super = klass->GetSuperClass();
Ian Rogers595799e2012-01-11 17:32:51 -08002360 for (int i = super->GetVTable()->GetLength() - 1; i >= 0; --i) {
2361 const Method* method = klass->GetVTable()->Get(i);
2362 if (method != super->GetVTable()->Get(i) &&
2363 !IsSameMethodSignatureInDifferentClassContexts(method, super, klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002364 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2365 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2366 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002367 return false;
2368 }
2369 }
2370 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002371 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2372 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2373 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002374 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2375 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002376 const Method* method = interface_entry->GetMethodArray()->Get(j);
Ian Rogers595799e2012-01-11 17:32:51 -08002377 if (!IsSameMethodSignatureInDifferentClassContexts(method, interface,
2378 method->GetDeclaringClass())) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002379 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2380 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2381 PrettyMethod(method).c_str(),
2382 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002383 return false;
2384 }
2385 }
2386 }
2387 }
2388 return true;
2389}
2390
Ian Rogers595799e2012-01-11 17:32:51 -08002391// Returns true if classes referenced by the signature of the method are the
2392// same classes in klass1 as they are in klass2.
2393bool ClassLinker::IsSameMethodSignatureInDifferentClassContexts(const Method* method,
2394 const Class* klass1,
2395 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002396 if (klass1 == klass2) {
2397 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002398 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002399 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002400 const DexFile::ProtoId& proto_id =
2401 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002402 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2403 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002404 if (descriptor == NULL) {
2405 break;
2406 }
2407 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2408 // Found a non-primitive type.
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 }
2414 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002415 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002416 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Ian Rogers595799e2012-01-11 17:32:51 -08002417 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002418 return false;
2419 }
2420 }
2421 return true;
2422}
2423
Ian Rogers595799e2012-01-11 17:32:51 -08002424// Returns true if the descriptor resolves to the same class in the context of klass1 and klass2.
2425bool ClassLinker::IsSameDescriptorInDifferentClassContexts(const char* descriptor,
2426 const Class* klass1,
2427 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002428 CHECK(descriptor != NULL);
2429 CHECK(klass1 != NULL);
2430 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002431 if (klass1 == klass2) {
2432 return true;
2433 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002434 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Ian Rogers595799e2012-01-11 17:32:51 -08002435 if (found1 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002436 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002437 }
Ian Rogers595799e2012-01-11 17:32:51 -08002438 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
2439 if (found2 == NULL) {
2440 Thread::Current()->ClearException();
2441 }
2442 return found1 == found2;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002443}
2444
Brian Carlstrom25c33252011-09-18 15:58:35 -07002445bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002446 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002447 if (!klass->IsInterface() && klass->HasSuperClass()) {
2448 Class* super_class = klass->GetSuperClass();
2449 if (super_class->GetStatus() != Class::kStatusInitialized) {
2450 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002451 Thread* self = Thread::Current();
2452 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002453 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002454 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002455 // TODO: check for a pending exception
2456 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002457 if (!can_run_clinit) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002458 // Don't set status to error when we can't run <clinit>.
2459 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing) << PrettyClass(klass);
2460 klass->SetStatus(Class::kStatusVerified);
2461 return false;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002462 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002463 klass->SetStatus(Class::kStatusError);
2464 klass->NotifyAll();
2465 return false;
2466 }
2467 }
2468 }
2469 return true;
2470}
2471
Brian Carlstrom25c33252011-09-18 15:58:35 -07002472bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002473 CHECK(c != NULL);
2474 if (c->IsInitialized()) {
2475 return true;
2476 }
2477
Elliott Hughes5f791332011-09-15 17:45:30 -07002478 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002479 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Ian Rogers595799e2012-01-11 17:32:51 -08002480 bool success = InitializeClass(c, can_run_clinit);
2481 if (!success) {
Ian Rogers1bddec32012-02-04 12:27:34 -08002482 CHECK(self->IsExceptionPending() || !can_run_clinit) << PrettyClass(c);
Ian Rogers595799e2012-01-11 17:32:51 -08002483 }
2484 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002485}
2486
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002487void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002488 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002489 const ClassLoader* cl = c->GetClassLoader();
2490 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002491 ClassDataItemIterator it(dex_file, class_data);
2492 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2493 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002494 }
2495}
2496
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002497void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002498 size_t num_static_fields = klass->NumStaticFields();
2499 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002500 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002501 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002502 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002503 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002504 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002505 return;
2506 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002507 ClassHelper kh(klass);
2508 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002509 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002510 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002511 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002512
Ian Rogers0571d352011-11-03 19:51:38 -07002513 if (it.HasNext()) {
2514 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2515 std::map<uint32_t, Field*> field_map;
2516 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2517 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2518 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002519 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002520 }
2521}
2522
Ian Rogersc2b44472011-12-14 21:17:17 -08002523bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002524 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002525 if (!LinkSuperClass(klass)) {
2526 return false;
2527 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002528 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002529 return false;
2530 }
2531 if (!LinkInstanceFields(klass)) {
2532 return false;
2533 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002534 if (!LinkStaticFields(klass)) {
2535 return false;
2536 }
2537 CreateReferenceInstanceOffsets(klass);
2538 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002539 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2540 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002541 return true;
2542}
2543
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002544bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002545 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002546 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2547 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
Ian Rogerscab01012012-01-10 17:35:46 -08002548 CHECK(class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002549 uint16_t super_class_idx = class_def->superclass_idx_;
2550 if (super_class_idx != DexFile::kDexNoIndex16) {
2551 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002552 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002553 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002554 return false;
2555 }
Ian Rogersbe125a92012-01-11 15:19:49 -08002556 // Verify
2557 if (!klass->CanAccess(super_class)) {
2558 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2559 "Class %s extended by class %s is inaccessible",
2560 PrettyDescriptor(super_class).c_str(),
2561 PrettyDescriptor(klass.get()).c_str());
2562 return false;
2563 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002564 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002565 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002566 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2567 if (interfaces != NULL) {
2568 for (size_t i = 0; i < interfaces->Size(); i++) {
2569 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2570 Class* interface = ResolveType(dex_file, idx, klass.get());
2571 if (interface == NULL) {
2572 DCHECK(Thread::Current()->IsExceptionPending());
2573 return false;
2574 }
2575 // Verify
2576 if (!klass->CanAccess(interface)) {
2577 // TODO: the RI seemed to ignore this in my testing.
2578 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2579 "Interface %s implemented by class %s is inaccessible",
2580 PrettyDescriptor(interface).c_str(),
2581 PrettyDescriptor(klass.get()).c_str());
2582 return false;
2583 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002584 }
2585 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002586 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002587 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002588 return true;
2589}
2590
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002591bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002592 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002593 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002594 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002595 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002596 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002597 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002598 return false;
2599 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002600 return true;
2601 }
2602 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002603 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002604 return false;
2605 }
2606 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002607 if (super->IsFinal() || super->IsInterface()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002608 Thread* self = Thread::Current();
2609 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002610 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002611 PrettyDescriptor(super).c_str(),
2612 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002613 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002614 return false;
2615 }
2616 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002617 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002618 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002619 PrettyDescriptor(super).c_str(),
2620 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002621 return false;
2622 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002623
2624 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2625 if (super->IsFinalizable()) {
2626 klass->SetFinalizable();
2627 }
2628
Elliott Hughes2da50362011-10-10 16:57:08 -07002629 // Inherit reference flags (if any) from the superclass.
2630 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2631 if (reference_flags != 0) {
2632 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2633 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002634 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002635 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002636 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002637 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002638 return false;
2639 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002640
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002641#ifndef NDEBUG
2642 // Ensure super classes are fully resolved prior to resolving fields..
2643 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002644 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002645 super = super->GetSuperClass();
2646 }
2647#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002648 return true;
2649}
2650
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002651// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002652bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002653 if (klass->IsInterface()) {
2654 // No vtable.
2655 size_t count = klass->NumVirtualMethods();
2656 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002657 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002658 return false;
2659 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002660 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002661 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002662 }
jeffhaobdb76512011-09-07 11:43:16 -07002663 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002664 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002665 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002666 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002667 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002668 }
2669 return true;
2670}
2671
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002672bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002673 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002674 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2675 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002676 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002677 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002678 SirtRef<ObjectArray<Method> > vtable(klass->GetSuperClass()->GetVTable()->CopyOf(max_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002679 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002680 MethodHelper local_mh(NULL, this);
2681 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002682 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002683 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002684 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002685 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002686 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002687 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002688 super_mh.ChangeMethod(super_method);
2689 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002690 // Verify
2691 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002692 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002693 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002694 PrettyDescriptor(klass.get()).c_str(),
2695 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002696 return false;
2697 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002698 vtable->Set(j, local_method);
2699 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002700 break;
2701 }
2702 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002703 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002704 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002705 vtable->Set(actual_count, local_method);
2706 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002707 actual_count += 1;
2708 }
2709 }
2710 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002711 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002712 return false;
2713 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002714 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002715 CHECK_LE(actual_count, max_count);
2716 if (actual_count < max_count) {
Ian Rogers30fab402012-01-23 15:43:46 -08002717 vtable.reset(vtable->CopyOf(actual_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002718 }
Ian Rogers30fab402012-01-23 15:43:46 -08002719 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002720 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002721 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002722 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002723 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002724 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002725 return false;
2726 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002727 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002728 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002729 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2730 vtable->Set(i, virtual_method);
2731 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002732 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002733 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002734 }
2735 return true;
2736}
2737
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002738bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002739 size_t super_ifcount;
2740 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002741 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002742 } else {
2743 super_ifcount = 0;
2744 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002745 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002746 ClassHelper kh(klass.get(), this);
2747 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2748 ifcount += num_interfaces;
2749 for (size_t i = 0; i < num_interfaces; i++) {
2750 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2751 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002752 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002753 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002754 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002755 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002756 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002757 return true;
2758 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002759 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002760 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002761 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2762 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogersb52b01a2012-01-12 17:01:38 -08002763 Class* super_interface = super_iftable->Get(i)->GetInterface();
2764 iftable->Set(i, AllocInterfaceEntry(super_interface));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002765 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002766 }
2767 // Flatten the interface inheritance hierarchy.
2768 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002769 for (size_t i = 0; i < num_interfaces; i++) {
2770 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002771 DCHECK(interface != NULL);
2772 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002773 ClassHelper ih(interface);
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002774 Thread* self = Thread::Current();
2775 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002776 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002777 PrettyDescriptor(klass.get()).c_str(),
2778 PrettyDescriptor(ih.GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002779 return false;
2780 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002781 // Check if interface is already in iftable
2782 bool duplicate = false;
2783 for (size_t j = 0; j < idx; j++) {
2784 Class* existing_interface = iftable->Get(j)->GetInterface();
2785 if (existing_interface == interface) {
2786 duplicate = true;
2787 break;
2788 }
2789 }
2790 if (!duplicate) {
2791 // Add this non-duplicate interface.
2792 iftable->Set(idx++, AllocInterfaceEntry(interface));
2793 // Add this interface's non-duplicate super-interfaces.
2794 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2795 Class* super_interface = interface->GetIfTable()->Get(j)->GetInterface();
2796 bool super_duplicate = false;
2797 for (size_t k = 0; k < idx; k++) {
2798 Class* existing_interface = iftable->Get(k)->GetInterface();
2799 if (existing_interface == super_interface) {
2800 super_duplicate = true;
2801 break;
2802 }
2803 }
2804 if (!super_duplicate) {
2805 iftable->Set(idx++, AllocInterfaceEntry(super_interface));
2806 }
2807 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002808 }
2809 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002810 // Shrink iftable in case duplicates were found
2811 if (idx < ifcount) {
2812 iftable.reset(iftable->CopyOf(idx));
2813 ifcount = idx;
2814 } else {
2815 CHECK_EQ(idx, ifcount);
2816 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002817 klass->SetIfTable(iftable.get());
Elliott Hughes4681c802011-09-25 18:04:37 -07002818
2819 // If we're an interface, we don't need the vtable pointers, so we're done.
2820 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002821 return true;
2822 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002823 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002824 MethodHelper vtable_mh(NULL, this);
2825 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002826 for (size_t i = 0; i < ifcount; ++i) {
2827 InterfaceEntry* interface_entry = iftable->Get(i);
2828 Class* interface = interface_entry->GetInterface();
2829 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2830 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002831 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002832 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2833 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002834 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002835 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002836 // For each method listed in the interface's method list, find the
2837 // matching method in our class's method list. We want to favor the
2838 // subclass over the superclass, which just requires walking
2839 // back from the end of the vtable. (This only matters if the
2840 // superclass defines a private method and this class redefines
2841 // it -- otherwise it would use the same vtable slot. In .dex files
2842 // those don't end up in the virtual method table, so it shouldn't
2843 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002844 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2845 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002846 vtable_mh.ChangeMethod(vtable_method);
2847 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002848 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002849 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002850 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002851 return false;
2852 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002853 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002854 break;
2855 }
2856 }
2857 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002858 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002859 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002860 Method* mir_method = miranda_list[mir];
2861 vtable_mh.ChangeMethod(mir_method);
2862 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002863 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002864 break;
2865 }
2866 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002867 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002868 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002869 miranda_method.reset(AllocMethod());
2870 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2871 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002872 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002873 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002874 }
2875 }
2876 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002877 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002878 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002879 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002880 klass->SetVirtualMethods((old_method_count == 0)
2881 ? AllocObjectArray<Method>(new_method_count)
2882 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002883
Ian Rogers30fab402012-01-23 15:43:46 -08002884 SirtRef<ObjectArray<Method> > vtable(klass->GetVTableDuringLinking());
2885 CHECK(vtable.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002886 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002887 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers30fab402012-01-23 15:43:46 -08002888 vtable.reset(vtable->CopyOf(new_vtable_count));
Elliott Hughes4681c802011-09-25 18:04:37 -07002889 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002890 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002891 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002892 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2893 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2894 klass->SetVirtualMethod(old_method_count + i, method);
2895 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002896 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002897 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002898 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002899 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002900
2901 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2902 for (int i = 0; i < vtable->GetLength(); ++i) {
2903 CHECK(vtable->Get(i) != NULL);
2904 }
2905
2906// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2907
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002908 return true;
2909}
2910
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002911bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2912 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002913 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002914}
2915
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002916bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2917 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002918 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002919 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002920 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002921 return success;
2922}
2923
Brian Carlstromdbc05252011-09-09 01:59:59 -07002924struct LinkFieldsComparator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002925 explicit LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002926 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002927 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002928 fh_->ChangeField(field1);
2929 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2930 fh_->ChangeField(field2);
2931 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002932 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2933 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2934 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2935 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002936 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2937 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2938 if (order1 != order2) {
2939 return order1 < order2;
2940 }
2941
2942 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002943 fh_->ChangeField(field1);
2944 StringPiece name1(fh_->GetName());
2945 fh_->ChangeField(field2);
2946 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002947 return name1 < name2;
2948 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002949
2950 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002951};
2952
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002953bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002954 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002955 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002956
2957 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002958 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002959
2960 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002961 size_t size;
2962 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002963 if (is_static) {
2964 size = klass->GetClassSize();
2965 field_offset = Class::FieldsOffset();
2966 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002967 Class* super_class = klass->GetSuperClass();
2968 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002969 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002970 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002971 }
2972 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002973 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002974
Brian Carlstromdbc05252011-09-09 01:59:59 -07002975 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002976
Brian Carlstromdbc05252011-09-09 01:59:59 -07002977 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002978 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002979 std::deque<Field*> grouped_and_sorted_fields;
2980 for (size_t i = 0; i < num_fields; i++) {
2981 grouped_and_sorted_fields.push_back(fields->Get(i));
2982 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002983 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002984 std::sort(grouped_and_sorted_fields.begin(),
2985 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002986 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002987
2988 // References should be at the front.
2989 size_t current_field = 0;
2990 size_t num_reference_fields = 0;
2991 for (; current_field < num_fields; current_field++) {
2992 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002993 fh.ChangeField(field);
2994 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002995 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002996 if (isPrimitive) {
2997 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002998 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002999 grouped_and_sorted_fields.pop_front();
3000 num_reference_fields++;
3001 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003002 field->SetOffset(field_offset);
3003 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003004 }
3005
3006 // Now we want to pack all of the double-wide fields together. If
3007 // we're not aligned, though, we want to shuffle one 32-bit field
3008 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07003009 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003010 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
3011 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003012 fh.ChangeField(field);
3013 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003014 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
3015 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003016 continue;
3017 }
3018 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003019 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003020 // drop the consumed field
3021 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
3022 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003023 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07003024 // whether we found a 32-bit field for padding or not, we advance
3025 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003026 }
3027
3028 // Alignment is good, shuffle any double-wide fields forward, and
3029 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07003030 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07003031 while (!grouped_and_sorted_fields.empty()) {
3032 Field* field = grouped_and_sorted_fields.front();
3033 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003034 fh.ChangeField(field);
3035 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003036 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07003037 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003038 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003039 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003040 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07003041 ? sizeof(uint64_t)
3042 : sizeof(uint32_t)));
3043 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003044 }
3045
Elliott Hughesadb460d2011-10-05 17:02:34 -07003046 // 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 -08003047 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
3048 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07003049 // We know there are no non-reference fields in the Reference classes, and we know
3050 // that 'referent' is alphabetically last, so this is easy...
3051 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003052 fh.ChangeField(fields->Get(num_fields - 1));
Elliott Hughesba8eee12012-01-24 20:25:24 -08003053 CHECK_STREQ(fh.GetName(), "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07003054 --num_reference_fields;
3055 }
3056
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003057#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07003058 // Make sure that all reference fields appear before
3059 // non-reference fields, and all double-wide fields are aligned.
3060 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07003061 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003062 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003063 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003064 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003065 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07003066 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07003067 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
3068 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003069 fh.ChangeField(field);
3070 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003071 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003072 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07003073 is_primitive = true; // We lied above, so we have to expect a lie here.
3074 }
3075 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07003076 if (!seen_non_ref) {
3077 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003078 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003079 }
Brian Carlstrombe977852011-07-19 14:54:54 -07003080 } else {
3081 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003082 }
3083 }
Brian Carlstrombe977852011-07-19 14:54:54 -07003084 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003085 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003086 }
3087#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003088 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003089 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003090 if (is_static) {
3091 klass->SetNumReferenceStaticFields(num_reference_fields);
3092 klass->SetClassSize(size);
3093 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003094 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003095 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003096 klass->SetObjectSize(size);
3097 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003098 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003099 return true;
3100}
3101
3102// Set the bitmap of reference offsets, refOffsets, from the ifields
3103// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003104void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003105 uint32_t reference_offsets = 0;
3106 Class* super_class = klass->GetSuperClass();
3107 if (super_class != NULL) {
3108 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003109 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003110 if (reference_offsets == CLASS_WALK_SUPER) {
3111 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003112 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003113 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003114 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003115 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003116}
3117
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003118void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003119 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003120}
3121
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003122void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003123 uint32_t reference_offsets) {
3124 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003125 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
3126 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003127 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003128 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003129 // All of the fields that contain object references are guaranteed
3130 // to be at the beginning of the fields list.
3131 for (size_t i = 0; i < num_reference_fields; ++i) {
3132 // Note that byte_offset is the offset from the beginning of
3133 // object, not the offset into instance data
3134 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003135 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003136 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
3137 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
3138 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07003139 CHECK_NE(new_bit, 0U);
3140 reference_offsets |= new_bit;
3141 } else {
3142 reference_offsets = CLASS_WALK_SUPER;
3143 break;
3144 }
3145 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003146 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003147 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003148 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003149 } else {
3150 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003151 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003152}
3153
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003154String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07003155 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003156 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003157 if (resolved != NULL) {
3158 return resolved;
3159 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003160 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
3161 int32_t utf16_length = dex_file.GetStringLength(string_id);
3162 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07003163 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003164 dex_cache->SetResolvedString(string_idx, string);
3165 return string;
3166}
3167
3168Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003169 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003170 DexCache* dex_cache,
3171 const ClassLoader* class_loader) {
3172 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003173 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07003174 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003175 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003176 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05003177 // TODO: we used to throw here if resolved's class loader was not the
3178 // boot class loader. This was to permit different classes with the
3179 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003180 dex_cache->SetResolvedType(type_idx, resolved);
3181 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08003182 CHECK(Thread::Current()->IsExceptionPending())
3183 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003184 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003185 }
3186 return resolved;
3187}
3188
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003189Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
3190 uint32_t method_idx,
3191 DexCache* dex_cache,
3192 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003193 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003194 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
3195 if (resolved != NULL) {
3196 return resolved;
3197 }
3198 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3199 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
3200 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07003201 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003202 return NULL;
3203 }
3204
Ian Rogers0571d352011-11-03 19:51:38 -07003205 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
3206 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003207 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003208 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003209 } else if (klass->IsInterface()) {
3210 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003211 } else {
3212 resolved = klass->FindVirtualMethod(name, signature);
3213 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003214 if (resolved != NULL) {
3215 dex_cache->SetResolvedMethod(method_idx, resolved);
3216 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003217 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003218 }
3219 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003220}
3221
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003222Field* ClassLinker::ResolveField(const DexFile& dex_file,
3223 uint32_t field_idx,
3224 DexCache* dex_cache,
3225 const ClassLoader* class_loader,
3226 bool is_static) {
3227 Field* resolved = dex_cache->GetResolvedField(field_idx);
3228 if (resolved != NULL) {
3229 return resolved;
3230 }
3231 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3232 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3233 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003234 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003235 return NULL;
3236 }
3237
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003238 const char* name = dex_file.GetFieldName(field_id);
3239 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003240 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003241 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003242 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003243 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003244 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003245 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003246 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003247 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08003248 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
3249 }
3250 return resolved;
3251}
3252
3253Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
3254 uint32_t field_idx,
3255 DexCache* dex_cache,
3256 const ClassLoader* class_loader) {
3257 Field* resolved = dex_cache->GetResolvedField(field_idx);
3258 if (resolved != NULL) {
3259 return resolved;
3260 }
3261 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3262 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3263 if (klass == NULL) {
3264 DCHECK(Thread::Current()->IsExceptionPending());
3265 return NULL;
3266 }
3267
3268 const char* name = dex_file.GetFieldName(field_id);
3269 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3270 resolved = klass->FindField(name, type);
3271 if (resolved != NULL) {
3272 dex_cache->SetResolvedField(field_idx, resolved);
3273 } else {
3274 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003275 }
3276 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07003277}
3278
Ian Rogersad25ac52011-10-04 19:13:33 -07003279const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
3280 Class* declaring_class = referrer->GetDeclaringClass();
3281 DexCache* dex_cache = declaring_class->GetDexCache();
3282 const DexFile& dex_file = FindDexFile(dex_cache);
3283 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3284 return dex_file.GetShorty(method_id.proto_idx_);
3285}
3286
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003287void ClassLinker::DumpAllClasses(int flags) const {
3288 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3289 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3290 std::vector<Class*> all_classes;
3291 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003292 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003293 typedef Table::const_iterator It; // TODO: C++0x auto
3294 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3295 all_classes.push_back(it->second);
3296 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003297 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3298 all_classes.push_back(it->second);
3299 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003300 }
3301
3302 for (size_t i = 0; i < all_classes.size(); ++i) {
3303 all_classes[i]->DumpClass(std::cerr, flags);
3304 }
3305}
3306
Elliott Hughescac6cc72011-11-03 20:31:21 -07003307void ClassLinker::DumpForSigQuit(std::ostream& os) const {
3308 MutexLock mu(classes_lock_);
3309 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3310 << classes_.size() << " allocated classes\n";
3311}
3312
Elliott Hughese27955c2011-08-26 15:21:24 -07003313size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003314 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003315 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003316}
3317
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003318pid_t ClassLinker::GetClassesLockOwner() {
3319 return classes_lock_.GetOwner();
3320}
3321
3322pid_t ClassLinker::GetDexLockOwner() {
3323 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003324}
3325
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003326void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3327 DCHECK(!init_done_);
3328
3329 DCHECK(klass != NULL);
3330 DCHECK(klass->GetClassLoader() == NULL);
3331
3332 DCHECK(class_roots_ != NULL);
3333 DCHECK(class_roots_->Get(class_root) == NULL);
3334 class_roots_->Set(class_root, klass);
3335}
3336
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003337} // namespace art