blob: f414c4b5944e31b381bd43494999d265b288553e [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Brian Carlstromd601af82012-01-06 10:15:19 -080019#include <fcntl.h>
20#include <sys/file.h>
21#include <sys/stat.h>
Brian Carlstromdbf05b72011-12-15 00:55:24 -080022#include <sys/types.h>
23#include <sys/wait.h>
24
Brian Carlstromdbc05252011-09-09 01:59:59 -070025#include <deque>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070026#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070027#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070028#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070029
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070030#include "casts.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070031#include "class_loader.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080032#include "debugger.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070033#include "dex_cache.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070034#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070035#include "dex_verifier.h"
36#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070037#include "intern_table.h"
Ian Rogers0571d352011-11-03 19:51:38 -070038#include "leb128.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070039#include "logging.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070040#include "oat_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070041#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080042#include "object_utils.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080043#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070044#include "runtime.h"
Ian Rogers466bb252011-10-14 03:29:56 -070045#include "runtime_support.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070046#include "ScopedLocalRef.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070047#include "space.h"
Brian Carlstrom40381fb2011-10-19 14:13:40 -070048#include "stack_indirect_reference_table.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070049#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070050#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070051#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070052#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070053
54namespace art {
55
Elliott Hughes4a2b4172011-09-20 17:08:25 -070056namespace {
57
Elliott Hughes362f9bc2011-10-17 18:56:41 -070058void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070059void ThrowNoClassDefFoundError(const char* fmt, ...) {
60 va_list args;
61 va_start(args, fmt);
62 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
63 va_end(args);
64}
65
Elliott Hughes362f9bc2011-10-17 18:56:41 -070066void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughese555dc02011-09-25 10:46:35 -070067void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070068 va_list args;
69 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070070 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070071 va_end(args);
72}
73
Elliott Hughes362f9bc2011-10-17 18:56:41 -070074void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070075void ThrowLinkageError(const char* fmt, ...) {
76 va_list args;
77 va_start(args, fmt);
78 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
79 va_end(args);
80}
81
Ian Rogers9f1ab122011-12-12 08:52:43 -080082void ThrowNoSuchMethodError(bool is_direct, Class* c, const StringPiece& name,
83 const StringPiece& signature) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080084 ClassHelper kh(c);
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070085 std::ostringstream msg;
Ian Rogers9f1ab122011-12-12 08:52:43 -080086 msg << "no " << (is_direct ? "direct" : "virtual") << " method " << name << "." << signature
87 << " in class " << kh.GetDescriptor() << " or its superclasses";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080088 std::string location(kh.GetLocation());
89 if (!location.empty()) {
90 msg << " (defined in " << location << ")";
Elliott Hughescc5f9a92011-09-28 19:17:29 -070091 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070092 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070093}
94
Ian Rogersb067ac22011-12-13 18:05:09 -080095void ThrowNoSuchFieldError(const StringPiece& scope, Class* c, const StringPiece& type,
Ian Rogers9f1ab122011-12-12 08:52:43 -080096 const StringPiece& name) {
97 ClassHelper kh(c);
98 std::ostringstream msg;
Ian Rogersb067ac22011-12-13 18:05:09 -080099 msg << "no " << scope << "field " << name << " of type " << type
Ian Rogers9f1ab122011-12-12 08:52:43 -0800100 << " in class " << kh.GetDescriptor() << " or its superclasses";
101 std::string location(kh.GetLocation());
102 if (!location.empty()) {
103 msg << " (defined in " << location << ")";
104 }
105 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchFieldError;", msg.str().c_str());
106}
107
Ian Rogerscab01012012-01-10 17:35:46 -0800108void ThrowNullPointerException(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
109void ThrowNullPointerException(const char* fmt, ...) {
110 va_list args;
111 va_start(args, fmt);
112 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NullPointerException;", fmt, args);
113 va_end(args);
114}
115
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700116void ThrowEarlierClassFailure(Class* c) {
117 /*
118 * The class failed to initialize on a previous attempt, so we want to throw
119 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
120 * failed in verification, in which case v2 5.4.1 says we need to re-throw
121 * the previous error.
122 */
123 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
124
Brian Carlstrom4d9716c2012-01-30 01:49:33 -0800125 CHECK(c->IsErroneous()) << PrettyClass(c);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700126 if (c->GetVerifyErrorClass() != NULL) {
127 // TODO: change the verifier to store an _instance_, with a useful detail message?
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800128 ClassHelper ve_ch(c->GetVerifyErrorClass());
129 std::string error_descriptor(ve_ch.GetDescriptor());
130 Thread::Current()->ThrowNewException(error_descriptor.c_str(), PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700131 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800132 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700133 }
134}
135
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700136void WrapExceptionInInitializer() {
137 JNIEnv* env = Thread::Current()->GetJniEnv();
138
139 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
140 CHECK(cause.get() != NULL);
141
142 env->ExceptionClear();
143
144 // TODO: add java.lang.Error to JniConstants?
145 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
146 CHECK(error_class.get() != NULL);
147 if (env->IsInstanceOf(cause.get(), error_class.get())) {
148 // We only wrap non-Error exceptions; an Error can just be used as-is.
149 env->Throw(cause.get());
150 return;
151 }
152
153 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
154 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
155 CHECK(eiie_class.get() != NULL);
156
157 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
158 CHECK(mid != NULL);
159
160 ScopedLocalRef<jthrowable> eiie(env,
161 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
162 env->Throw(eiie.get());
163}
164
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800165static size_t Hash(const char* s) {
166 // This is the java.lang.String hashcode for convenience, not interoperability.
167 size_t hash = 0;
168 for (; *s != '\0'; ++s) {
169 hash = hash * 31 + *s;
170 }
171 return hash;
172}
173
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700174} // namespace
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700175
Elliott Hughes418d20f2011-09-22 14:00:39 -0700176const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700177 "Ljava/lang/Class;",
178 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700179 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700180 "[Ljava/lang/Object;",
181 "Ljava/lang/String;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700182 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700183 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700184 "Ljava/lang/reflect/Field;",
185 "Ljava/lang/reflect/Method;",
Ian Rogers466bb252011-10-14 03:29:56 -0700186 "Ljava/lang/reflect/Proxy;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700187 "Ljava/lang/ClassLoader;",
188 "Ldalvik/system/BaseDexClassLoader;",
189 "Ldalvik/system/PathClassLoader;",
Ian Rogers5167c972012-02-03 10:41:20 -0800190 "Ljava/lang/Throwable;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700191 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700192 "Z",
193 "B",
194 "C",
195 "D",
196 "F",
197 "I",
198 "J",
199 "S",
200 "V",
201 "[Z",
202 "[B",
203 "[C",
204 "[D",
205 "[F",
206 "[I",
207 "[J",
208 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700209 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700210};
211
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800212ClassLinker* ClassLinker::Create(const std::string& boot_class_path, InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700213 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800214 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700215 class_linker->Init(boot_class_path);
216 return class_linker.release();
217}
218
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800219ClassLinker* ClassLinker::Create(InternTable* intern_table) {
220 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700221 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700222 return class_linker.release();
223}
224
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800225ClassLinker::ClassLinker(InternTable* intern_table)
226 : dex_lock_("ClassLinker dex lock"),
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700227 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700228 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700229 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700230 init_done_(false),
231 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700232 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700233}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700234
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700235void CreateClassPath(const std::string& class_path,
236 std::vector<const DexFile*>& class_path_vector) {
237 std::vector<std::string> parsed;
238 Split(class_path, ':', parsed);
239 for (size_t i = 0; i < parsed.size(); ++i) {
240 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700241 if (dex_file == NULL) {
242 LOG(WARNING) << "Failed to open dex file " << parsed[i];
243 } else {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700244 class_path_vector.push_back(dex_file);
245 }
246 }
247}
248
249void ClassLinker::Init(const std::string& boot_class_path) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800250 VLOG(startup) << "ClassLinker::InitFrom entering boot_class_path=" << boot_class_path;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700251
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700252 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700253
Elliott Hughes30646832011-10-13 16:59:46 -0700254 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700255 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
256 CHECK(java_lang_Class.get() != NULL);
257 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700258 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700259 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700260
Elliott Hughes418d20f2011-09-22 14:00:39 -0700261 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700262 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
263 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700264
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700265 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700266 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
267 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700268 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700269 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700270 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700271
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700272 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700273 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
274 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700275
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700276 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700277 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700278
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700279 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700280 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
281 char_array_class->SetComponentType(char_class.get());
282 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700283
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700284 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700285 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
286 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700287 java_lang_String->SetObjectSize(sizeof(String));
288 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400289
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700290 // Create storage for root classes, save away our work so far (requires
291 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700292 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700293 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700294 SetClassRoot(kJavaLangClass, java_lang_Class.get());
295 SetClassRoot(kJavaLangObject, java_lang_Object.get());
296 SetClassRoot(kClassArrayClass, class_array_class.get());
297 SetClassRoot(kObjectArrayClass, object_array_class.get());
298 SetClassRoot(kCharArrayClass, char_array_class.get());
299 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700300
301 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700302 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
303 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
304 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
305 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
306 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
307 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
308 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
309 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700310
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700311 // Create array interface entries to populate once we can load system classes
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700312 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700313
314 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700315 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700316 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700317 IntArray::SetArrayClass(int_array_class.get());
318 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700319
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700320 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700321
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700322 // setup boot_class_path_ and register class_path now that we can
323 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700324 std::vector<const DexFile*> boot_class_path_vector;
325 CreateClassPath(boot_class_path, boot_class_path_vector);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700326 CHECK_NE(0U, boot_class_path_vector.size());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700327 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
328 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700329 CHECK(dex_file != NULL);
330 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700331 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700332
Elliott Hughes80609252011-09-23 17:24:51 -0700333 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700334 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700335 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700336 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700337 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700338 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
339
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700340 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
341 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700342 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700343 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700344 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700345 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700346
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700347 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700348 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700349 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700350 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700351 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700352 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700353
354 // now we can use FindSystemClass
355
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700356 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700357 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700358 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700359
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700360 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700361 java_lang_Object->SetStatus(Class::kStatusNotReady);
362 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700363 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700364 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
365 java_lang_String->SetStatus(Class::kStatusNotReady);
366 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700367 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700368 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
369
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700370 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700371 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
372 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
373
374 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
375 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
376
377 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700378 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700379
380 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
381 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
382
383 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700384 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700385
386 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
387 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
388
389 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
390 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
391
392 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
393 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
394
Elliott Hughes418d20f2011-09-22 14:00:39 -0700395 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700396 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700397
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700398 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700399 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700400
401 // Setup the single, global copies of "interfaces" and "iftable"
402 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
403 CHECK(java_lang_Cloneable != NULL);
404 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
405 CHECK(java_io_Serializable != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700406 // We assume that Cloneable/Serializable don't have superinterfaces --
407 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700408 // supers as well.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800409 array_iftable_->Set(0, AllocInterfaceEntry(java_lang_Cloneable));
410 array_iftable_->Set(1, AllocInterfaceEntry(java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700411
Elliott Hughes418d20f2011-09-22 14:00:39 -0700412 // Sanity check Class[] and Object[]'s interfaces
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800413 ClassHelper kh(class_array_class.get(), this);
414 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
415 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
416 kh.ChangeClass(object_array_class.get());
417 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
418 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
Elliott Hughes80609252011-09-23 17:24:51 -0700419 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700420 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700421 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700422 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700423
Elliott Hughes80609252011-09-23 17:24:51 -0700424 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
425 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700426 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700427
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700428 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700429 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700430 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700431
432 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700433 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700434 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700435
Ian Rogers466bb252011-10-14 03:29:56 -0700436 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
437
438 // Create java.lang.reflect.Proxy root
439 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
440 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
441
Brian Carlstrom1f870082011-08-23 16:02:11 -0700442 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700443 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
444 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700445 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700446 java_lang_ref_FinalizerReference->SetAccessFlags(
447 java_lang_ref_FinalizerReference->GetAccessFlags() |
448 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700449 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700450 java_lang_ref_PhantomReference->SetAccessFlags(
451 java_lang_ref_PhantomReference->GetAccessFlags() |
452 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700453 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700454 java_lang_ref_SoftReference->SetAccessFlags(
455 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700456 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700457 java_lang_ref_WeakReference->SetAccessFlags(
458 java_lang_ref_WeakReference->GetAccessFlags() |
459 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700460
Brian Carlstromaded5f72011-10-07 17:15:04 -0700461 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700462 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700463 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700464 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
465
466 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
467 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
468 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
469
470 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
471 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
472 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
473 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
474
Ian Rogers5167c972012-02-03 10:41:20 -0800475 // Set up java.lang.Throwable and java.lang.StackTraceElement as a convenience
476 SetClassRoot(kJavaLangThrowable, FindSystemClass("Ljava/lang/Throwable;"));
477 Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700478 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
479 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700480 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700481
Brian Carlstroma663ea52011-08-19 23:33:41 -0700482 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700483
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800484 VLOG(startup) << "ClassLinker::InitFrom exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700485}
486
487void ClassLinker::FinishInit() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800488 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700489
490 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700491 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700492 // as the types of the field can't be resolved prior to the runtime being
493 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700494 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700495 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700496 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
497
Elliott Hughesadb460d2011-10-05 17:02:34 -0700498 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
499
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800500 const DexFile& java_lang_dex = FindDexFile(java_lang_ref_Reference->GetDexCache());
501
Brian Carlstrom16192862011-09-12 17:50:06 -0700502 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800503 FieldHelper fh(pendingNext, this);
504 CHECK_STREQ(fh.GetName(), "pendingNext");
505 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
506 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700507
508 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800509 fh.ChangeField(queue);
510 CHECK_STREQ(fh.GetName(), "queue");
511 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
512 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700513
514 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800515 fh.ChangeField(queueNext);
516 CHECK_STREQ(fh.GetName(), "queueNext");
517 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
518 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700519
520 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800521 fh.ChangeField(referent);
522 CHECK_STREQ(fh.GetName(), "referent");
523 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
524 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700525
526 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800527 fh.ChangeField(zombie);
528 CHECK_STREQ(fh.GetName(), "zombie");
529 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
530 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700531
532 Heap::SetReferenceOffsets(referent->GetOffset(),
533 queue->GetOffset(),
534 queueNext->GetOffset(),
535 pendingNext->GetOffset(),
536 zombie->GetOffset());
537
Brian Carlstroma663ea52011-08-19 23:33:41 -0700538 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700539 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700540 ClassRoot class_root = static_cast<ClassRoot>(i);
541 Class* klass = GetClassRoot(class_root);
542 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700543 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700544 // note SetClassRoot does additional validation.
545 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700546 }
547
Elliott Hughes92f14b22011-10-06 12:29:54 -0700548 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700549
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700550 // disable the slow paths in FindClass and CreatePrimitiveClass now
551 // that Object, Class, and Object[] are setup
552 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700553
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800554 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700555}
556
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700557void ClassLinker::RunRootClinits() {
558 Thread* self = Thread::Current();
559 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
560 Class* c = GetClassRoot(ClassRoot(i));
561 if (!c->IsArrayClass() && !c->IsPrimitive()) {
562 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700563 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700564 }
565 }
566}
567
Brian Carlstromd601af82012-01-06 10:15:19 -0800568bool ClassLinker::GenerateOatFile(const std::string& dex_filename,
569 int oat_fd,
570 const std::string& oat_cache_filename) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800571 std::string dex2oat_string("/system/bin/dex2oat");
572#ifndef NDEBUG
573 dex2oat_string += 'd';
574#endif
575 const char* dex2oat = dex2oat_string.c_str();
576
577 const char* class_path = Runtime::Current()->GetClassPath().c_str();
578
579 std::string boot_image_option_string("--boot-image=");
Ian Rogers30fab402012-01-23 15:43:46 -0800580 boot_image_option_string += Heap::GetSpaces()[0]->AsImageSpace()->GetImageFilename();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800581 const char* boot_image_option = boot_image_option_string.c_str();
582
583 std::string dex_file_option_string("--dex-file=");
Brian Carlstromd601af82012-01-06 10:15:19 -0800584 dex_file_option_string += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800585 const char* dex_file_option = dex_file_option_string.c_str();
586
Brian Carlstromd601af82012-01-06 10:15:19 -0800587 std::string oat_fd_option_string("--oat-fd=");
Brian Carlstrom866c8622012-01-06 16:35:13 -0800588 StringAppendF(&oat_fd_option_string, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800589 const char* oat_fd_option = oat_fd_option_string.c_str();
590
591 std::string oat_name_option_string("--oat-name=");
592 oat_name_option_string += oat_cache_filename;
593 const char* oat_name_option = oat_name_option_string.c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800594
jeffhao262bf462011-10-20 18:36:32 -0700595 // fork and exec dex2oat
596 pid_t pid = fork();
597 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800598 // no allocation allowed between fork and exec
Ian Rogers725aee52012-01-11 11:56:56 -0800599
600 // change process groups, so we don't get reaped by ProcessManager
601 setpgid(0, 0);
602
jeffhao10037c82012-01-23 15:06:23 -0800603 VLOG(class_linker) << dex2oat
604 << " --runtime-arg -Xms64m"
605 << " --runtime-arg -Xmx64m"
606 << " --runtime-arg -classpath"
607 << " --runtime-arg " << class_path
608 << " " << boot_image_option
609 << " " << dex_file_option
610 << " " << oat_fd_option
611 << " " << oat_name_option;
612
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800613 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700614 "--runtime-arg", "-Xms64m",
615 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500616 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800617 "--runtime-arg", class_path,
618 boot_image_option,
619 dex_file_option,
Brian Carlstromd601af82012-01-06 10:15:19 -0800620 oat_fd_option,
621 oat_name_option,
jeffhao262bf462011-10-20 18:36:32 -0700622 NULL);
623
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800624 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
Brian Carlstromd601af82012-01-06 10:15:19 -0800625 return false;
jeffhao262bf462011-10-20 18:36:32 -0700626 } else {
627 // wait for dex2oat to finish
628 int status;
629 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
630 if (got_pid != pid) {
631 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
Brian Carlstromd601af82012-01-06 10:15:19 -0800632 return false;
jeffhao262bf462011-10-20 18:36:32 -0700633 }
634 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800635 LOG(ERROR) << dex2oat << " failed with dex-file=" << dex_filename;
636 return false;
jeffhao262bf462011-10-20 18:36:32 -0700637 }
638 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800639 return true;
jeffhao262bf462011-10-20 18:36:32 -0700640}
641
Brian Carlstrom866c8622012-01-06 16:35:13 -0800642void ClassLinker::RegisterOatFile(const OatFile& oat_file) {
643 MutexLock mu(dex_lock_);
644 RegisterOatFileLocked(oat_file);
645}
646
647void ClassLinker::RegisterOatFileLocked(const OatFile& oat_file) {
648 dex_lock_.AssertHeld();
649 oat_files_.push_back(&oat_file);
650}
651
Ian Rogers30fab402012-01-23 15:43:46 -0800652OatFile* ClassLinker::OpenOat(const ImageSpace* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700653 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700654 const Runtime* runtime = Runtime::Current();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700655 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800656 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
657 // check the down cast
658 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700659 std::string oat_filename;
660 oat_filename += runtime->GetHostPrefix();
661 oat_filename += oat_location->ToModifiedUtf8();
Ian Rogers30fab402012-01-23 15:43:46 -0800662 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBegin());
663 VLOG(startup) << "ClassLinker::OpenOat entering oat_filename=" << oat_filename;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700664 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700665 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700666 return NULL;
667 }
668 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
669 uint32_t image_oat_checksum = image_header.GetOatChecksum();
670 if (oat_checksum != image_oat_checksum) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800671 LOG(ERROR) << "Failed to match oat file checksum " << std::hex << oat_checksum
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700672 << " to expected oat checksum " << std::hex << oat_checksum
673 << " in image";
674 return NULL;
675 }
Brian Carlstrom866c8622012-01-06 16:35:13 -0800676 RegisterOatFileLocked(*oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800677 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700678 return oat_file;
679}
680
Brian Carlstromae826982011-11-09 01:33:42 -0800681const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800682 return FindOpenedOatFileFromDexLocation(dex_file.GetLocation(),
683 dex_file.GetLocationChecksum());
684}
685
686const OatFile* ClassLinker::FindOpenedOatFileFromDexLocation(const std::string& dex_location,
687 uint32_t dex_location_checksum) {
Brian Carlstromae826982011-11-09 01:33:42 -0800688 for (size_t i = 0; i < oat_files_.size(); i++) {
689 const OatFile* oat_file = oat_files_[i];
690 DCHECK(oat_file != NULL);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800691 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, false);
692 if (oat_dex_file != NULL
693 && oat_dex_file->GetDexFileLocationChecksum() == dex_location_checksum) {
Brian Carlstromae826982011-11-09 01:33:42 -0800694 return oat_file;
695 }
696 }
697 return NULL;
698}
699
Brian Carlstromd601af82012-01-06 10:15:19 -0800700class LockedFd {
701 public:
702 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
703 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
704 if (fd == -1) {
705 PLOG(ERROR) << "Failed to open file '" << name << "'";
706 return NULL;
707 }
708 fchmod(fd, mode);
709
710 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
711 // try to lock non-blocking so we can log if we need may need to block
712 int result = flock(fd, LOCK_EX | LOCK_NB);
713 if (result == -1) {
714 LOG(WARNING) << "sleeping while locking file " << name;
715 // retry blocking
716 result = flock(fd, LOCK_EX);
717 }
718 if (result == -1) {
719 PLOG(ERROR) << "Failed to lock file '" << name << "'";
720 close(fd);
721 return NULL;
722 }
723 return new LockedFd(fd);
724 }
725
726 int GetFd() const {
727 return fd_;
728 }
729
730 ~LockedFd() {
731 if (fd_ != -1) {
732 int result = flock(fd_, LOCK_UN);
733 if (result == -1) {
734 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
735 }
736 close(fd_);
737 }
738 }
739
740 private:
741 explicit LockedFd(int fd) : fd_(fd) {}
742
743 int fd_;
744};
745
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800746static const DexFile* FindDexFileInOatLocation(const std::string& dex_location,
747 uint32_t dex_location_checksum,
748 const std::string& oat_location) {
749 UniquePtr<OatFile> oat_file(OatFile::Open(oat_location, "", NULL));
750 if (oat_file.get() == NULL) {
751 return NULL;
752 }
753 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
754 if (oat_dex_file == NULL) {
755 return NULL;
756 }
757 if (oat_dex_file->GetDexFileLocationChecksum() != dex_location_checksum) {
758 return NULL;
759 }
760 Runtime::Current()->GetClassLinker()->RegisterOatFile(*oat_file.release());
761 return oat_dex_file->OpenDexFile();
762}
763
764const DexFile* ClassLinker::FindOrCreateOatFileForDexLocation(const std::string& dex_location,
765 const std::string& oat_location) {
766 uint32_t dex_location_checksum;
767 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) {
768 LOG(ERROR) << "Failed to compute checksum '" << dex_location << "'";
769 return NULL;
770 }
771
772 // Check if we already have an up-to-date output file
773 const DexFile* dex_file = FindDexFileInOatLocation(dex_location,
774 dex_location_checksum,
775 oat_location);
776 if (dex_file != NULL) {
777 return dex_file;
778 }
779
780 // Generate the output oat file for the dex file
781 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
782 UniquePtr<File> file(OS::OpenFile(oat_location.c_str(), true));
783 if (file.get() == NULL) {
784 LOG(ERROR) << "Failed to create oat file: " << oat_location;
785 return NULL;
786 }
787 if (!class_linker->GenerateOatFile(dex_location, file->Fd(), oat_location)) {
788 LOG(ERROR) << "Failed to generate oat file: " << oat_location;
789 return NULL;
790 }
791 // Open the oat from file descriptor we passed to GenerateOatFile
792 if (lseek(file->Fd(), 0, SEEK_SET) != 0) {
793 LOG(ERROR) << "Failed to seek to start of generated oat file: " << oat_location;
794 return NULL;
795 }
796 const OatFile* oat_file = OatFile::Open(*file.get(), oat_location, NULL);
797 if (oat_file == NULL) {
798 LOG(ERROR) << "Failed to open generated oat file: " << oat_location;
799 return NULL;
800 }
801 class_linker->RegisterOatFile(*oat_file);
802 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
803 if (oat_dex_file == NULL) {
804 LOG(ERROR) << "Failed to find dex file in generated oat file: " << oat_location;
805 return NULL;
806 }
807 return oat_dex_file->OpenDexFile();
808}
809
810const DexFile* ClassLinker::FindDexFileInOatFileFromDexLocation(const std::string& dex_location) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700811 MutexLock mu(dex_lock_);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800812
813 uint32_t dex_location_checksum;
814 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) {
815 LOG(WARNING) << "Failed to compute checksum: " << dex_location;
816 return NULL;
817 }
818
819 const OatFile* open_oat_file = FindOpenedOatFileFromDexLocation(dex_location, dex_location_checksum);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800820 if (open_oat_file != NULL) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800821 return open_oat_file->GetOatDexFile(dex_location)->OpenDexFile();
Brian Carlstromae826982011-11-09 01:33:42 -0800822 }
823
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800824 // Look for an existing file first next to dex and in art-cache
825 std::string oat_filename(OatFile::DexFilenameToOatFilename(dex_location));
826 const OatFile* oat_file(FindOatFileFromOatLocation(oat_filename));
827 if (oat_file != NULL) {
828 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
829 if (dex_location_checksum == oat_dex_file->GetDexFileLocationChecksum()) {
830 return oat_file->GetOatDexFile(dex_location)->OpenDexFile();
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700831 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800832 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
833 << " checksum ( " << std::hex << oat_dex_file->GetDexFileLocationChecksum()
834 << ") mismatch with " << dex_location
835 << " (" << std::hex << dex_location_checksum << ")--- regenerating";
836 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
837 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
Brian Carlstromd601af82012-01-06 10:15:19 -0800838 }
jeffhao262bf462011-10-20 18:36:32 -0700839 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800840 // Try to generate oat file if it wasn't found or was obsolete.
841 std::string oat_cache_filename(GetArtCacheFilenameOrDie(oat_filename));
842 return FindOrCreateOatFileForDexLocation(dex_location, oat_cache_filename);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700843}
844
Brian Carlstromae826982011-11-09 01:33:42 -0800845const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700846 for (size_t i = 0; i < oat_files_.size(); i++) {
847 const OatFile* oat_file = oat_files_[i];
848 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800849 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700850 return oat_file;
851 }
852 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700853 return NULL;
854}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700855
Brian Carlstromae826982011-11-09 01:33:42 -0800856const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
jeffhaof6174e82012-01-31 16:14:17 -0800857 MutexLock mu(dex_lock_);
858 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
859 if (oat_file != NULL) {
860 return oat_file;
861 }
862
863 oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700864 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800865 if (oat_location.empty() || oat_location[0] != '/') {
866 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700867 return NULL;
868 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700869
Brian Carlstroma9f19782011-10-13 00:14:47 -0700870 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Elliott Hughes95572412011-12-13 18:14:20 -0800871 std::string cache_location(GetArtCacheFilenameOrDie(oat_location));
Brian Carlstromae826982011-11-09 01:33:42 -0800872 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700873 if (oat_file != NULL) {
874 return oat_file;
875 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700876 oat_file = OatFile::Open(cache_location, "", NULL);
877 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800878 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700879 return NULL;
880 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700881 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700882
Brian Carlstromae826982011-11-09 01:33:42 -0800883 CHECK(oat_file != NULL) << oat_location;
jeffhaof6174e82012-01-31 16:14:17 -0800884 RegisterOatFileLocked(*oat_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700885 return oat_file;
886}
887
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700888void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800889 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700890 CHECK(!init_done_);
891
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700892 const std::vector<Space*>& spaces = Heap::GetSpaces();
893 for (size_t i = 0; i < spaces.size(); i++) {
Ian Rogers30fab402012-01-23 15:43:46 -0800894 if (spaces[i]->IsImageSpace()) {
895 ImageSpace* space = spaces[i]->AsImageSpace();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700896 OatFile* oat_file = OpenOat(space);
897 CHECK(oat_file != NULL) << "Failed to open oat file for image";
898 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
899 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
900
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800901 if (i == 0) {
902 // Special case of setting up the String class early so that we can test arbitrary objects
903 // as being Strings or not
Ian Rogers30fab402012-01-23 15:43:46 -0800904 Class* java_lang_String = space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800905 ->AsObjectArray<Class>()->Get(kJavaLangString);
906 String::SetClass(java_lang_String);
907 }
908
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700909 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
910 static_cast<uint32_t>(dex_caches->GetLength()));
911 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700912 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800913 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom89521892011-12-07 22:05:07 -0800914 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
915 const DexFile* dex_file = oat_dex_file->OpenDexFile();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700916 if (dex_file == NULL) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800917 LOG(FATAL) << "Failed to open dex file " << dex_file_location
918 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700919 }
920
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800921 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700922
Brian Carlstromdf143242011-10-10 18:05:34 -0700923 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700924 }
925 }
926 }
927
Brian Carlstroma663ea52011-08-19 23:33:41 -0700928 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
929 DCHECK(heap_bitmap != NULL);
930
Brian Carlstroma663ea52011-08-19 23:33:41 -0700931 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700932 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700933
934 // reinit class_roots_
Ian Rogers30fab402012-01-23 15:43:46 -0800935 Object* class_roots_object =
936 spaces[0]->AsImageSpace()->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700937 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700938
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800939 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700940 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
941 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800942 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700943 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700944 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700945 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
946 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
947 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
948 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
949 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
950 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
951 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
952 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700953 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Ian Rogers5167c972012-02-03 10:41:20 -0800954 Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700955 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700956
957 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700958
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800959 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700960}
961
Brian Carlstrom78128a62011-09-15 17:21:19 -0700962void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700963 DCHECK(obj != NULL);
964 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700965 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700966
Elliott Hughesdbb40792011-11-18 17:05:22 -0800967 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700968 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700969 return;
970 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700971 if (obj->IsClass()) {
972 // restore class to ClassLinker::classes_ table
973 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800974 ClassHelper kh(klass, class_linker);
Brian Carlstrom07bb8552012-01-18 22:10:50 -0800975 Class* existing = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
976 DCHECK(existing == NULL) << kh.GetDescriptor();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700977 return;
978 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700979}
980
981// Keep in sync with InitCallback. Anything we visit, we need to
982// reinit references to when reinitializing a ClassLinker from a
983// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700984void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
985 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700986
987 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700988 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700989 }
990
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700991 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700992 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700993 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700994 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700995 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700996 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700997 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700998 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700999
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001000 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001001}
1002
Elliott Hughesa2155262011-11-16 16:26:58 -08001003void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
1004 MutexLock mu(classes_lock_);
1005 typedef Table::const_iterator It; // TODO: C++0x auto
1006 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
1007 if (!visitor(it->second, arg)) {
1008 return;
1009 }
1010 }
1011 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
1012 if (!visitor(it->second, arg)) {
1013 return;
1014 }
1015 }
1016}
1017
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001018ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001019 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001020 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -07001021 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001022 BooleanArray::ResetArrayClass();
1023 ByteArray::ResetArrayClass();
1024 CharArray::ResetArrayClass();
1025 DoubleArray::ResetArrayClass();
1026 FloatArray::ResetArrayClass();
1027 IntArray::ResetArrayClass();
1028 LongArray::ResetArrayClass();
1029 ShortArray::ResetArrayClass();
1030 PathClassLoader::ResetClass();
Ian Rogers5167c972012-02-03 10:41:20 -08001031 Throwable::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001032 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001033 STLDeleteElements(&boot_class_path_);
1034 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001035}
1036
1037DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001038 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
1039 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001040 return NULL;
1041 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001042 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
1043 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001044 return NULL;
1045 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001046 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
1047 if (strings.get() == NULL) {
1048 return NULL;
1049 }
1050 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
1051 if (types.get() == NULL) {
1052 return NULL;
1053 }
1054 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
1055 if (methods.get() == NULL) {
1056 return NULL;
1057 }
1058 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
1059 if (fields.get() == NULL) {
1060 return NULL;
1061 }
1062 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
1063 if (code_and_direct_methods.get() == NULL) {
1064 return NULL;
1065 }
1066 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
1067 if (initialized_static_storage.get() == NULL) {
1068 return NULL;
1069 }
1070
1071 dex_cache->Init(location.get(),
1072 strings.get(),
1073 types.get(),
1074 methods.get(),
1075 fields.get(),
1076 code_and_direct_methods.get(),
1077 initialized_static_storage.get());
1078 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001079}
1080
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001081CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
1082 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -07001083}
1084
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001085InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
1086 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001087 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
1088 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001089 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001090 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001091}
1092
Brian Carlstrom4873d462011-08-21 15:23:39 -07001093Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
1094 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001095 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001096 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001097 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001098 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001099}
1100
Brian Carlstrom4873d462011-08-21 15:23:39 -07001101Class* ClassLinker::AllocClass(size_t class_size) {
1102 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001103}
1104
Jesse Wilson35baaab2011-08-10 16:18:03 -04001105Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001106 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -07001107}
1108
1109Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001110 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001111}
1112
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001113ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
1114 return ObjectArray<StackTraceElement>::Alloc(
1115 GetClassRoot(kJavaLangStackTraceElementArrayClass),
1116 length);
1117}
1118
Brian Carlstromaded5f72011-10-07 17:15:04 -07001119Class* EnsureResolved(Class* klass) {
1120 DCHECK(klass != NULL);
1121 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -07001122 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001123 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001124 ObjectLock lock(klass);
1125 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001126 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001127 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001128 PrettyDescriptor(klass).c_str());
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001129 klass->SetStatus(Class::kStatusError);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001130 return NULL;
1131 }
1132 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001133 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001134 lock.Wait();
1135 }
1136 }
1137 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001138 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001139 return NULL;
1140 }
1141 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001142 CHECK(klass->IsResolved()) << PrettyClass(klass);
1143 CHECK(!self->IsExceptionPending())
1144 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
1145 return klass;
1146}
1147
Elliott Hughesdb7d5e92011-12-16 18:47:37 -08001148Class* ClassLinker::FindSystemClass(const char* descriptor) {
1149 return FindClass(descriptor, NULL);
1150}
1151
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001152Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001153 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001154 Thread* self = Thread::Current();
1155 DCHECK(self != NULL);
1156 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001157 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001158 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1159 // for primitive classes that aren't backed by dex files.
1160 return FindPrimitiveClass(descriptor[0]);
1161 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001162 // Find the class in the loaded classes table.
1163 Class* klass = LookupClass(descriptor, class_loader);
1164 if (klass != NULL) {
1165 return EnsureResolved(klass);
1166 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001167 // Class is not yet loaded.
1168 if (descriptor[0] == '[') {
1169 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001170
Jesse Wilson47daf872011-11-23 11:42:45 -05001171 } else if (class_loader == NULL) {
1172 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1173 if (pair.second != NULL) {
1174 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1175 }
1176
1177 } else if (ClassLoader::UseCompileTimeClassPath()) {
1178 // first try the boot class path
1179 Class* system_class = FindSystemClass(descriptor);
1180 if (system_class != NULL) {
1181 return system_class;
1182 }
1183 CHECK(self->IsExceptionPending());
1184 self->ClearException();
1185
1186 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001187 const std::vector<const DexFile*>& class_path
1188 = ClassLoader::GetCompileTimeClassPath(class_loader);
1189 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001190 if (pair.second != NULL) {
1191 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001192 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001193
1194 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001195 std::string class_name_string(DescriptorToDot(descriptor));
Elliott Hughes09d4d012012-02-03 17:44:20 -08001196 ScopedThreadStateChange tsc(self, Thread::kNative);
Elliott Hughes748382f2012-01-26 18:07:38 -08001197 JNIEnv* env = self->GetJniEnv();
Jesse Wilson47daf872011-11-23 11:42:45 -05001198 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1199 CHECK(c.get() != NULL);
1200 // TODO: cache method?
1201 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1202 CHECK(mid != NULL);
1203 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1204 if (class_name_object.get() == NULL) {
1205 return NULL;
1206 }
1207 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
Ian Rogers761bfa82012-01-11 10:14:05 -08001208 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid,
1209 class_name_object.get()));
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001210 if (env->ExceptionCheck()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001211 // If the ClassLoader threw, pass that exception up.
1212 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001213 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001214 // broken loader - throw NPE to be compatible with Dalvik
1215 ThrowNullPointerException("ClassLoader.loadClass returned null for %s",
1216 class_name_string.c_str());
1217 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001218 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08001219 // success, return Class*
Ian Rogers6b0870d2011-12-15 19:38:12 -08001220 return Decode<Class*>(env, result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001221 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001222 }
1223
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001224 ThrowNoClassDefFoundError("Class %s not found", PrintableString(StringPiece(descriptor)).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001225 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001226}
1227
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001228Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001229 const ClassLoader* class_loader,
1230 const DexFile& dex_file,
1231 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001232 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001233 // Load the class from the dex file.
1234 if (!init_done_) {
1235 // finish up init of hand crafted class_roots_
1236 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001237 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001238 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001239 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001240 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001241 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001242 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001243 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001244 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001245 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001246 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001247 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001248 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001249 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001250 }
1251 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001252 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001253 }
1254 klass->SetDexCache(FindDexCache(dex_file));
1255 LoadClass(dex_file, dex_class_def, klass, class_loader);
1256 // Check for a pending exception during load
1257 Thread* self = Thread::Current();
1258 if (self->IsExceptionPending()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001259 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001260 return NULL;
1261 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001262 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001263 klass->SetClinitThreadId(self->GetTid());
1264 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001265 Class* existing = InsertClass(descriptor, klass.get(), false);
1266 if (existing != NULL) {
1267 // We failed to insert because we raced with another thread.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001268 klass->SetClinitThreadId(0);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001269 klass.reset(existing);
1270 return EnsureResolved(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001271 }
1272 // Finish loading (if necessary) by finding parents
1273 CHECK(!klass->IsLoaded());
1274 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1275 // Loading failed.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001276 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001277 lock.NotifyAll();
1278 return NULL;
1279 }
1280 CHECK(klass->IsLoaded());
1281 // Link the class (if necessary)
1282 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001283 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001284 // Linking failed.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001285 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001286 lock.NotifyAll();
1287 return NULL;
1288 }
1289 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001290
1291 /*
1292 * We send CLASS_PREPARE events to the debugger from here. The
1293 * definition of "preparation" is creating the static fields for a
1294 * class and initializing them to the standard default values, but not
1295 * executing any code (that comes later, during "initialization").
1296 *
1297 * We did the static preparation in LinkClass.
1298 *
1299 * The class has been prepared and resolved but possibly not yet verified
1300 * at this point.
1301 */
1302 Dbg::PostClassPrepare(klass.get());
1303
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001304 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001305}
1306
Brian Carlstrom4873d462011-08-21 15:23:39 -07001307// Precomputes size that will be needed for Class, matching LinkStaticFields
1308size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1309 const DexFile::ClassDef& dex_class_def) {
1310 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001311 size_t num_ref = 0;
1312 size_t num_32 = 0;
1313 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001314 if (class_data != NULL) {
1315 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1316 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001317 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001318 char c = descriptor[0];
1319 if (c == 'L' || c == '[') {
1320 num_ref++;
1321 } else if (c == 'J' || c == 'D') {
1322 num_64++;
1323 } else {
1324 num_32++;
1325 }
1326 }
1327 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001328 // start with generic class data
1329 size_t size = sizeof(Class);
1330 // follow with reference fields which must be contiguous at start
1331 size += (num_ref * sizeof(uint32_t));
1332 // if there are 64-bit fields to add, make sure they are aligned
1333 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1334 if (num_32 != 0) {
1335 // use an available 32-bit field for padding
1336 num_32--;
1337 }
1338 size += sizeof(uint32_t); // either way, we are adding a word
1339 DCHECK_EQ(size, RoundUp(size, 8));
1340 }
1341 // tack on any 64-bit fields now that alignment is assured
1342 size += (num_64 * sizeof(uint64_t));
1343 // tack on any remaining 32-bit fields
1344 size += (num_32 * sizeof(uint32_t));
1345 return size;
1346}
1347
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001348void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001349 // Every kind of method should at least get an invoke stub from the oat_method.
1350 // non-abstract methods also get their code pointers.
1351 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001352 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001353
1354 if (method->IsAbstract()) {
1355 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1356 return;
1357 }
1358 if (method->IsNative()) {
1359 // unregistering restores the dlsym lookup stub
1360 method->UnregisterNative();
jeffhao26c0a1a2012-01-17 16:28:33 -08001361 }
1362
1363 if (Runtime::Current()->IsMethodTracingActive()) {
1364#if defined(__arm__)
1365 Trace* tracer = Runtime::Current()->GetTracer();
1366 void* trace_stub = reinterpret_cast<void*>(art_trace_entry_from_code);
1367 tracer->SaveAndUpdateCode(method.get(), trace_stub);
1368#else
1369 UNIMPLEMENTED(WARNING);
1370#endif
Brian Carlstrom92827a52011-10-10 15:50:01 -07001371 }
1372}
1373
Brian Carlstromf615a612011-07-23 12:50:34 -07001374void ClassLinker::LoadClass(const DexFile& dex_file,
1375 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001376 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001377 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001378 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001379 CHECK(klass->GetDexCache() != NULL);
1380 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001381 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001382 CHECK(descriptor != NULL);
1383
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001384 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001385 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001386 // Make sure that none of our runtime-only flags are set.
1387 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001388 klass->SetAccessFlags(access_flags);
1389 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001390 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001391 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001392
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001393 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001394
Ian Rogers0571d352011-11-03 19:51:38 -07001395 // Load fields fields.
1396 const byte* class_data = dex_file.GetClassData(dex_class_def);
1397 if (class_data == NULL) {
1398 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001399 }
Ian Rogers0571d352011-11-03 19:51:38 -07001400 ClassDataItemIterator it(dex_file, class_data);
1401 if (it.NumStaticFields() != 0) {
1402 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1403 }
1404 if (it.NumInstanceFields() != 0) {
1405 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1406 }
1407 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1408 SirtRef<Field> sfield(AllocField());
1409 klass->SetStaticField(i, sfield.get());
1410 LoadField(dex_file, it, klass, sfield);
1411 }
1412 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1413 SirtRef<Field> ifield(AllocField());
1414 klass->SetInstanceField(i, ifield.get());
1415 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001416 }
1417
Brian Carlstromaded5f72011-10-07 17:15:04 -07001418 UniquePtr<const OatFile::OatClass> oat_class;
1419 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001420 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
1421 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << descriptor;
1422 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1423 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << descriptor;
1424 uint32_t class_def_index;
1425 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1426 CHECK(found) << dex_file.GetLocation() << " " << descriptor;
1427 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
1428 CHECK(oat_class.get() != NULL) << dex_file.GetLocation() << " " << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001429 }
Ian Rogers0571d352011-11-03 19:51:38 -07001430 // Load methods.
1431 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001432 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001433 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001434 }
Ian Rogers0571d352011-11-03 19:51:38 -07001435 if (it.NumVirtualMethods() != 0) {
1436 // TODO: append direct methods to class object
1437 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001438 }
Ian Rogers0571d352011-11-03 19:51:38 -07001439 size_t method_index = 0;
1440 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1441 SirtRef<Method> method(AllocMethod());
1442 klass->SetDirectMethod(i, method.get());
1443 LoadMethod(dex_file, it, klass, method);
1444 if (oat_class.get() != NULL) {
1445 LinkCode(method, oat_class.get(), method_index);
1446 }
1447 method_index++;
1448 }
1449 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1450 SirtRef<Method> method(AllocMethod());
1451 klass->SetVirtualMethod(i, method.get());
1452 LoadMethod(dex_file, it, klass, method);
1453 if (oat_class.get() != NULL) {
1454 LinkCode(method, oat_class.get(), method_index);
1455 }
1456 method_index++;
1457 }
1458 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001459}
1460
Ian Rogers0571d352011-11-03 19:51:38 -07001461void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1462 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001463 uint32_t field_idx = it.GetMemberIndex();
1464 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001465 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001466 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001467}
1468
Ian Rogers0571d352011-11-03 19:51:38 -07001469void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1470 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001471 uint32_t method_idx = it.GetMemberIndex();
1472 dst->SetDexMethodIndex(method_idx);
1473 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001474 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001475
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001476
1477 StringPiece method_name(dex_file.GetMethodName(method_id));
1478 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001479 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1480 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001481
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001482 if (method_name == "finalize") {
1483 // Create the prototype for a signature of "()V"
1484 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1485 if (void_string_id != NULL) {
1486 const DexFile::TypeId* void_type_id =
1487 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1488 if (void_type_id != NULL) {
1489 std::vector<uint16_t> no_args;
1490 const DexFile::ProtoId* finalizer_proto =
1491 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1492 if (finalizer_proto != NULL) {
1493 // We have the prototype in the dex file
1494 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1495 klass->SetFinalizable();
1496 } else {
1497 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1498 // The Enum class declares a "final" finalize() method to prevent subclasses from
1499 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1500 // subclasses, so we exclude it here.
1501 // We also want to avoid setting the flag on Object, where we know that finalize() is
1502 // empty.
1503 if (klass_descriptor != "Ljava/lang/Object;" &&
1504 klass_descriptor != "Ljava/lang/Enum;") {
1505 klass->SetFinalizable();
1506 }
1507 }
1508 }
1509 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001510 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001511 }
Ian Rogers0571d352011-11-03 19:51:38 -07001512 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001513 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001514
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001515 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1516 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1517 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1518 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1519 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1520 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001521}
1522
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001523void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001524 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1525 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001526}
1527
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001528void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1529 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001530 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001531 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001532}
1533
Brian Carlstromaded5f72011-10-07 17:15:04 -07001534bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001535 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001536 for (size_t i = 0; i != dex_files_.size(); ++i) {
1537 if (dex_files_[i] == &dex_file) {
1538 return true;
1539 }
1540 }
1541 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001542}
1543
Brian Carlstromaded5f72011-10-07 17:15:04 -07001544bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001545 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001546 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001547}
1548
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001549void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001550 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001551 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001552 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001553 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001554 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001555}
1556
Brian Carlstromaded5f72011-10-07 17:15:04 -07001557void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001558 {
1559 MutexLock mu(dex_lock_);
1560 if (IsDexFileRegisteredLocked(dex_file)) {
1561 return;
1562 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001563 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001564 // Don't alloc while holding the lock, since allocation may need to
1565 // suspend all threads and another thread may need the dex_lock_ to
1566 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001567 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001568 {
1569 MutexLock mu(dex_lock_);
1570 if (IsDexFileRegisteredLocked(dex_file)) {
1571 return;
1572 }
1573 RegisterDexFileLocked(dex_file, dex_cache);
1574 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001575}
1576
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001577void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001578 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001579 RegisterDexFileLocked(dex_file, dex_cache);
1580}
1581
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001582const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001583 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001584 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001585 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1586 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001587 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001588 }
1589 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001590 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001591 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001592}
1593
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001594DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001595 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001596 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001597 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001598 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001599 }
1600 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001601 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001602 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001603}
1604
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001605Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1606 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001607 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001608 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001609 CHECK(primitive_class != NULL);
1610 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001611 primitive_class->SetPrimitiveType(type);
1612 primitive_class->SetStatus(Class::kStatusInitialized);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001613 Class* existing = InsertClass(descriptor, primitive_class, false);
1614 CHECK(existing == NULL) << "InitPrimitiveClass(" << descriptor << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001615 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001616}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001617
Brian Carlstrombe977852011-07-19 14:54:54 -07001618// Create an array class (i.e. the class object for the array, not the
1619// array itself). "descriptor" looks like "[C" or "[[[[B" or
1620// "[Ljava/lang/String;".
1621//
1622// If "descriptor" refers to an array of primitives, look up the
1623// primitive type's internally-generated class object.
1624//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001625// "class_loader" is the class loader of the class that's referring to
1626// us. It's used to ensure that we're looking for the element type in
1627// the right context. It does NOT become the class loader for the
1628// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001629//
1630// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001631Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001632 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001633
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001634 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001635 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001636 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001637 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001638 return NULL;
1639 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001640
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001641 // See if the component type is already loaded. Array classes are
1642 // always associated with the class loader of their underlying
1643 // element type -- an array of Strings goes with the loader for
1644 // java/lang/String -- so we need to look for it there. (The
1645 // caller should have checked for the existence of the class
1646 // before calling here, but they did so with *their* class loader,
1647 // not the component type's loader.)
1648 //
1649 // If we find it, the caller adds "loader" to the class' initiating
1650 // loader list, which should prevent us from going through this again.
1651 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001652 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001653 // are the same, because our caller (FindClass) just did the
1654 // lookup. (Even if we get this wrong we still have correct behavior,
1655 // because we effectively do this lookup again when we add the new
1656 // class to the hash table --- necessary because of possible races with
1657 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001658 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001659 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001660 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001661 return new_class;
1662 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001663 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001664
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001665 // Fill out the fields in the Class.
1666 //
1667 // It is possible to execute some methods against arrays, because
1668 // all arrays are subclasses of java_lang_Object_, so we need to set
1669 // up a vtable. We can just point at the one in java_lang_Object_.
1670 //
1671 // Array classes are simple enough that we don't need to do a full
1672 // link step.
1673
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001674 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001675 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001676 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001677 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001678 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001679 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001680 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001681 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001682 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001683 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001684 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001685 }
1686 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001687 if (new_class.get() == NULL) {
1688 new_class.reset(AllocClass(sizeof(Class)));
1689 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001690 return NULL;
1691 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001692 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001693 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001694 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001695 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001696 new_class->SetSuperClass(java_lang_Object);
1697 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001698 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001699 new_class->SetClassLoader(component_type->GetClassLoader());
1700 new_class->SetStatus(Class::kStatusInitialized);
1701 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001702 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001703
1704
1705 // All arrays have java/lang/Cloneable and java/io/Serializable as
1706 // interfaces. We need to set that up here, so that stuff like
1707 // "instanceof" works right.
1708 //
1709 // Note: The GC could run during the call to FindSystemClass,
1710 // so we need to make sure the class object is GC-valid while we're in
1711 // there. Do this by clearing the interface list so the GC will just
1712 // think that the entries are null.
1713
1714
1715 // Use the single, global copies of "interfaces" and "iftable"
1716 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001717 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001718 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001719
1720 // Inherit access flags from the component type. Arrays can't be
1721 // used as a superclass or interface, so we want to add "final"
1722 // and remove "interface".
1723 //
1724 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001725 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001726 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001727 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1728 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001729
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001730 Class* existing = InsertClass(descriptor, new_class.get(), false);
1731 if (existing == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001732 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001733 }
1734 // Another thread must have loaded the class after we
1735 // started but before we finished. Abandon what we've
1736 // done.
1737 //
1738 // (Yes, this happens.)
1739
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001740 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001741}
1742
1743Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001744 switch (Primitive::GetType(type)) {
1745 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001746 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001747 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001748 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001749 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001750 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001751 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001752 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001753 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001754 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001755 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001756 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001757 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001758 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001759 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001760 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001761 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001762 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001763 case Primitive::kPrimNot:
1764 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001765 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001766 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001767 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001768 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001769}
1770
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001771Class* ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001772 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001773 DexCache* dex_cache = klass->GetDexCache();
1774 std::string source;
1775 if (dex_cache != NULL) {
1776 source += " from ";
1777 source += dex_cache->GetLocation()->ToModifiedUtf8();
1778 }
1779 LOG(INFO) << "Loaded class " << descriptor << source;
1780 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001781 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001782 MutexLock mu(classes_lock_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001783 Table& classes = image_class ? image_classes_ : classes_;
1784 Class* existing = LookupClass(descriptor.data(), klass->GetClassLoader(), hash, classes);
1785#ifndef NDEBUG
1786 // Check we don't have the class in the other table in error
1787 Table& other_classes = image_class ? classes_ : image_classes_;
1788 CHECK(LookupClass(descriptor.data(), klass->GetClassLoader(), hash, other_classes) == NULL);
1789#endif
1790 if (existing != NULL) {
1791 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07001792 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001793 classes.insert(std::make_pair(hash, klass));
1794 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001795}
1796
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001797bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1798 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001799 MutexLock mu(classes_lock_);
Elliott Hughese5448b52012-01-18 16:44:06 -08001800 typedef Table::iterator It; // TODO: C++0x auto
Brian Carlstromae826982011-11-09 01:33:42 -08001801 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001802 ClassHelper kh;
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001803 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001804 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001805 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001806 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001807 classes_.erase(it);
1808 return true;
1809 }
1810 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001811 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001812 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001813 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001814 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001815 image_classes_.erase(it);
1816 return true;
1817 }
1818 }
1819 return false;
1820}
1821
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001822Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1823 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001824 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001825 // TODO: determine if its better to search classes_ or image_classes_ first
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001826 Class* klass = LookupClass(descriptor, class_loader, hash, classes_);
1827 if (klass != NULL) {
1828 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001829 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001830 return LookupClass(descriptor, class_loader, hash, image_classes_);
1831}
1832
1833Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader,
1834 size_t hash, const Table& classes) {
1835 ClassHelper kh(NULL, this);
1836 typedef Table::const_iterator It; // TODO: C++0x auto
1837 for (It it = classes.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001838 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001839 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001840 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001841#ifndef NDEBUG
1842 for (++it; it != end && it->first == hash; ++it) {
1843 kh.ChangeClass(it->second);
1844 CHECK(!(strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader))
1845 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
1846 << PrettyClass(it->second) << " " << it->second << " " << it->second->GetClassLoader();
1847 }
1848#endif
Ian Rogers5d76c432011-10-31 21:42:49 -07001849 return klass;
1850 }
1851 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001852 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001853}
1854
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001855void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001856 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001857 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001858 MutexLock mu(classes_lock_);
1859 typedef Table::const_iterator It; // TODO: C++0x auto
1860 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001861 ClassHelper kh(NULL, this);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001862 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001863 Class* klass = it->second;
1864 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001865 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001866 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001867 }
1868 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001869 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001870 Class* klass = it->second;
1871 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001872 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001873 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001874 }
1875 }
1876}
1877
Ian Rogersc20a83e2012-01-18 18:15:32 -08001878#ifndef NDEBUG
1879static void CheckMethodsHaveGcMaps(Class* klass) {
1880 if (!Runtime::Current()->IsStarted()) {
1881 return;
1882 }
1883 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
1884 Method* method = klass->GetDirectMethod(i);
1885 if (!method->IsNative() && !method->IsAbstract()) {
1886 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1887 }
1888 }
1889 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
1890 Method* method = klass->GetVirtualMethod(i);
1891 if (!method->IsNative() && !method->IsAbstract()) {
1892 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1893 }
1894 }
1895}
1896#else
1897static void CheckMethodsHaveGcMaps(Class* klass) {
1898}
1899#endif
1900
jeffhao98eacac2011-09-14 16:11:53 -07001901void ClassLinker::VerifyClass(Class* klass) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001902 ObjectLock lock(klass);
1903
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001904 // TODO: assert that the monitor on the Class is held
jeffhao98eacac2011-09-14 16:11:53 -07001905 if (klass->IsVerified()) {
1906 return;
1907 }
1908
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001909 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved) << PrettyClass(klass);
jeffhao98eacac2011-09-14 16:11:53 -07001910 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001911
Ian Rogers1c5eb702012-02-01 09:18:34 -08001912 // Verify super class
1913 Class* super = klass->GetSuperClass();
1914 std::string error_msg;
1915 if (super != NULL) {
1916 // Acquire lock to prevent races on verifying the super class
1917 ObjectLock lock(super);
1918
1919 if (!super->IsVerified() && !super->IsErroneous()) {
1920 Runtime::Current()->GetClassLinker()->VerifyClass(super);
1921 }
1922 if (!super->IsVerified()) {
1923 error_msg = "Rejecting class ";
1924 error_msg += PrettyDescriptor(klass);
1925 error_msg += " that attempts to sub-class erroneous class ";
1926 error_msg += PrettyDescriptor(super);
1927 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
1928 Thread* self = Thread::Current();
1929 SirtRef<Throwable> cause(self->GetException());
1930 if (cause.get() != NULL) {
1931 self->ClearException();
1932 }
1933 self->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
1934 if (cause.get() != NULL) {
1935 self->GetException()->SetCause(cause.get());
1936 }
1937 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyDescriptor(klass);
1938 klass->SetStatus(Class::kStatusError);
1939 return;
1940 }
1941 }
1942
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001943 // Try to use verification information from oat file, otherwise do runtime verification
1944 const DexFile& dex_file = FindDexFile(klass->GetDexCache());
Ian Rogers1c5eb702012-02-01 09:18:34 -08001945 if (VerifyClassUsingOatFile(dex_file, klass) ||
1946 verifier::DexVerifier::VerifyClass(klass, error_msg)) {
Ian Rogersc4762272012-02-01 15:55:55 -08001947 DCHECK(!Thread::Current()->IsExceptionPending());
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001948 // Make sure all classes referenced by catch blocks are resolved
1949 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001950 klass->SetStatus(Class::kStatusVerified);
Ian Rogersc20a83e2012-01-18 18:15:32 -08001951 // Sanity check that a verified class has GC maps on all methods
1952 CheckMethodsHaveGcMaps(klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001953 } else {
Ian Rogers09f6b562012-01-31 21:58:52 -08001954 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass)
Ian Rogers1c5eb702012-02-01 09:18:34 -08001955 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
1956 << " because: " << error_msg;
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001957 Thread* self = Thread::Current();
Ian Rogersc4762272012-02-01 15:55:55 -08001958 CHECK(!self->IsExceptionPending());
Ian Rogers1c5eb702012-02-01 09:18:34 -08001959 self->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
1960 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyDescriptor(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001961 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001962 }
jeffhao98eacac2011-09-14 16:11:53 -07001963}
1964
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001965bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, Class* klass) {
1966 if (!Runtime::Current()->IsStarted()) {
1967 return false;
1968 }
1969 if (ClassLoader::UseCompileTimeClassPath()) {
1970 return false;
1971 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001972 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
1973 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001974 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001975 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001976 const char* descriptor = ClassHelper(klass).GetDescriptor();
1977 uint32_t class_def_index;
1978 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001979 CHECK(found) << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001980 UniquePtr<const OatFile::OatClass> oat_class(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001981 CHECK(oat_class.get() != NULL)
1982 << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001983 Class::Status status = oat_class->GetStatus();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001984 if (status == Class::kStatusVerified || status == Class::kStatusInitialized) {
1985 return true;
1986 }
Ian Rogersc4762272012-02-01 15:55:55 -08001987 if (status == Class::kStatusError) {
1988 // Compile time verification failed. Compile time verification can fail because we have
1989 // incomplete type information. Consider the following:
1990 // class ... {
1991 // Foo x;
1992 // .... () {
1993 // if (...) {
1994 // v1 gets assigned a type of resolved class Foo
1995 // } else {
1996 // v1 gets assigned a type of unresolved class Bar
1997 // }
1998 // iput x = v1
1999 // } }
2000 // when we merge v1 following the if-the-else it results in Conflict
2001 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
2002 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
2003 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
2004 // at compile time).
2005 return false;
2006 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002007 if (status == Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08002008 // Status is uninitialized if we couldn't determine the status at compile time, for example,
2009 // not loading the class.
2010 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
2011 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002012 return false;
2013 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002014 LOG(FATAL) << "Unexpected class status: " << status
2015 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
2016
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002017 return false;
2018}
2019
2020void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, Class* klass) {
2021 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
2022 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
2023 }
2024 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
2025 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
2026 }
2027}
2028
2029void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, Method* method) {
2030 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
2031 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
2032 if (code_item == NULL) {
2033 return; // native or abstract method
2034 }
2035 if (code_item->tries_size_ == 0) {
2036 return; // nothing to process
2037 }
2038 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
2039 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2040 ClassLinker* linker = Runtime::Current()->GetClassLinker();
2041 for (uint32_t idx = 0; idx < handlers_size; idx++) {
2042 CatchHandlerIterator iterator(handlers_ptr);
2043 for (; iterator.HasNext(); iterator.Next()) {
2044 // Ensure exception types are resolved so that they don't need resolution to be delivered,
2045 // unresolved exception types will be ignored by exception delivery
2046 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
2047 Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
2048 if (exception_type == NULL) {
2049 DCHECK(Thread::Current()->IsExceptionPending());
2050 Thread::Current()->ClearException();
2051 }
2052 }
2053 }
2054 handlers_ptr = iterator.EndDataPointer();
2055 }
2056}
2057
Ian Rogersc2b44472011-12-14 21:17:17 -08002058static void CheckProxyConstructor(Method* constructor);
2059static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
2060
Jesse Wilson95caa792011-10-12 18:14:17 -04002061Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002062 ClassLoader* loader, ObjectArray<Method>* methods,
2063 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08002064 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002065 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08002066 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04002067 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002068 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002069 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002070 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002071 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07002072 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002073 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08002074
2075 klass->SetStatus(Class::kStatusIdx);
2076
2077 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
2078
2079 // Create static field that holds throws, instance fields are inherited
2080 klass->SetSFields(AllocObjectArray<Field>(1));
2081 SirtRef<Field> sfield(AllocField());
2082 klass->SetStaticField(0, sfield.get());
2083 sfield->SetDexFieldIndex(-1);
2084 sfield->SetDeclaringClass(klass.get());
2085 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002086
Ian Rogers466bb252011-10-14 03:29:56 -07002087 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04002088 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002089 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04002090
Ian Rogers466bb252011-10-14 03:29:56 -07002091 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04002092 size_t num_virtual_methods = methods->GetLength();
2093 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
2094 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002095 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002096 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04002097 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002098
2099 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
2100 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
2101 DCHECK(!Thread::Current()->IsExceptionPending());
2102
2103 // Link the fields and virtual methods, creating vtable and iftables
2104 if (!LinkClass(klass, interfaces)) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002105 klass->SetStatus(Class::kStatusError);
Jesse Wilson95caa792011-10-12 18:14:17 -04002106 return NULL;
2107 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002108 sfield->SetObject(NULL, throws); // initialize throws field
2109 klass->SetStatus(Class::kStatusInitialized);
2110
2111 // sanity checks
2112#ifndef NDEBUG
2113 bool debug = true;
2114#else
2115 bool debug = false;
2116#endif
2117 if (debug) {
2118 CHECK(klass->GetIFields() == NULL);
2119 CheckProxyConstructor(klass->GetDirectMethod(0));
2120 for (size_t i = 0; i < num_virtual_methods; ++i) {
2121 SirtRef<Method> prototype(methods->Get(i));
2122 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
2123 }
Brian Carlstrom89521892011-12-07 22:05:07 -08002124 std::string throws_field_name("java.lang.Class[][] ");
Ian Rogersc2b44472011-12-14 21:17:17 -08002125 throws_field_name += name->ToModifiedUtf8();
2126 throws_field_name += ".throws";
2127 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
2128
2129 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
2130 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
2131 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002132 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04002133}
2134
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002135std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
2136 DCHECK(proxy_class->IsProxyClass());
2137 String* name = proxy_class->GetName();
2138 DCHECK(name != NULL);
2139 return DotToDescriptor(name->ToModifiedUtf8().c_str());
2140}
2141
2142
2143Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07002144 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07002145 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04002146 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07002147 Method* proxy_constructor = proxy_direct_methods->Get(2);
2148 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
2149 // code_ too)
2150 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
2151 // Make this constructor public and fix the class to be our Proxy version
2152 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002153 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08002154 return constructor;
2155}
2156
2157static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07002158 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002159 MethodHelper mh(constructor);
2160 CHECK_STREQ(mh.GetName(), "<init>");
Elliott Hughesba8eee12012-01-24 20:25:24 -08002161 CHECK_EQ(mh.GetSignature(), std::string("(Ljava/lang/reflect/InvocationHandler;)V"));
Ian Rogers466bb252011-10-14 03:29:56 -07002162 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04002163}
2164
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002165Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
2166 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
2167 // prototype method
2168 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
2169 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07002170 // as necessary
2171 Method* method = down_cast<Method*>(prototype->Clone());
2172
2173 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
2174 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002175 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07002176 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002177
Ian Rogers466bb252011-10-14 03:29:56 -07002178 // At runtime the method looks like a reference and argument saving method, clone the code
2179 // related parameters from this method.
2180 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
2181 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
2182 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
2183 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
2184 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08002185 return method;
2186}
Jesse Wilson95caa792011-10-12 18:14:17 -04002187
Ian Rogersc2b44472011-12-14 21:17:17 -08002188static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07002189 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002190 CHECK(!prototype->IsFinal());
2191 CHECK(method->IsFinal());
2192 CHECK(!method->IsAbstract());
2193 MethodHelper mh(method);
2194 const char* method_name = mh.GetName();
2195 const char* method_shorty = mh.GetShorty();
2196 Class* method_return = mh.GetReturnType();
2197
2198 mh.ChangeMethod(prototype.get());
2199
2200 CHECK_STREQ(mh.GetName(), method_name);
2201 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07002202
2203 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002204 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04002205}
2206
Brian Carlstrom25c33252011-09-18 15:58:35 -07002207bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002208 CHECK(klass->IsResolved() || klass->IsErroneous())
2209 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002210
Carl Shapirob5573532011-07-12 18:22:59 -07002211 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002212
Brian Carlstrom25c33252011-09-18 15:58:35 -07002213 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002214 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002215 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002216 ObjectLock lock(klass);
2217
Brian Carlstromd1422f82011-09-28 11:37:09 -07002218 if (klass->GetStatus() == Class::kStatusInitialized) {
2219 return true;
2220 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002221
Brian Carlstromd1422f82011-09-28 11:37:09 -07002222 if (klass->IsErroneous()) {
2223 ThrowEarlierClassFailure(klass);
2224 return false;
2225 }
2226
2227 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07002228 VerifyClass(klass);
2229 if (klass->GetStatus() != Class::kStatusVerified) {
Ian Rogers595799e2012-01-11 17:32:51 -08002230 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002231 return false;
2232 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002233 }
2234
Brian Carlstrom25c33252011-09-18 15:58:35 -07002235 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
2236 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002237 // if the class has a <clinit> but we can't run it during compilation,
Ian Rogers595799e2012-01-11 17:32:51 -08002238 // don't bother going to kStatusInitializing. We return true to maintain
2239 // the invariant that a false result implies there is a pending exception.
2240 return true;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002241 }
2242
Brian Carlstromd1422f82011-09-28 11:37:09 -07002243 // If the class is kStatusInitializing, either this thread is
2244 // initializing higher up the stack or another thread has beat us
2245 // to initializing and we need to wait. Either way, this
2246 // invocation of InitializeClass will not be responsible for
2247 // running <clinit> and will return.
2248 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002249 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002250 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002251 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002252 return true;
2253 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002254 // No. That's fine. Wait for another thread to finish initializing.
2255 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002256 }
2257
2258 if (!ValidateSuperClassDescriptors(klass)) {
2259 klass->SetStatus(Class::kStatusError);
2260 return false;
2261 }
2262
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002263 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified) << PrettyClass(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002264
Elliott Hughesdcc24742011-09-07 14:02:44 -07002265 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002266 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002267 }
2268
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002269 uint64_t t0 = NanoTime();
2270
Brian Carlstrom25c33252011-09-18 15:58:35 -07002271 if (!InitializeSuperClass(klass, can_run_clinit)) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002272 CHECK(klass->IsErroneous());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002273 return false;
2274 }
2275
2276 InitializeStaticFields(klass);
2277
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002278 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002279 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002280 }
2281
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002282 uint64_t t1 = NanoTime();
2283
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002284 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002285 {
2286 ObjectLock lock(klass);
2287
2288 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002289 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002290 klass->SetStatus(Class::kStatusError);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002291 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002292 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002293 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2294 RuntimeStats* thread_stats = self->GetStats();
2295 ++global_stats->class_init_count;
2296 ++thread_stats->class_init_count;
2297 global_stats->class_init_time_ns += (t1 - t0);
2298 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002299 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002300 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002301 ClassHelper kh(klass);
2302 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002303 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002304 }
2305 lock.NotifyAll();
2306 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002307 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002308}
2309
Brian Carlstromd1422f82011-09-28 11:37:09 -07002310bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
2311 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002312 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002313 lock.Wait();
2314
2315 // When we wake up, repeat the test for init-in-progress. If
2316 // there's an exception pending (only possible if
2317 // "interruptShouldThrow" was set), bail out.
2318 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002319 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002320 klass->SetStatus(Class::kStatusError);
2321 return false;
2322 }
2323 // Spurious wakeup? Go back to waiting.
2324 if (klass->GetStatus() == Class::kStatusInitializing) {
2325 continue;
2326 }
2327 if (klass->IsErroneous()) {
2328 // The caller wants an exception, but it was thrown in a
2329 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002330 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002331 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002332 return false;
2333 }
2334 if (klass->IsInitialized()) {
2335 return true;
2336 }
2337 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2338 }
2339 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2340}
2341
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002342bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2343 if (klass->IsInterface()) {
2344 return true;
2345 }
2346 // begin with the methods local to the superclass
2347 if (klass->HasSuperClass() &&
2348 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2349 const Class* super = klass->GetSuperClass();
Ian Rogers595799e2012-01-11 17:32:51 -08002350 for (int i = super->GetVTable()->GetLength() - 1; i >= 0; --i) {
2351 const Method* method = klass->GetVTable()->Get(i);
2352 if (method != super->GetVTable()->Get(i) &&
2353 !IsSameMethodSignatureInDifferentClassContexts(method, super, klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002354 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2355 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2356 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002357 return false;
2358 }
2359 }
2360 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002361 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2362 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2363 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002364 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2365 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002366 const Method* method = interface_entry->GetMethodArray()->Get(j);
Ian Rogers595799e2012-01-11 17:32:51 -08002367 if (!IsSameMethodSignatureInDifferentClassContexts(method, interface,
2368 method->GetDeclaringClass())) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002369 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2370 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2371 PrettyMethod(method).c_str(),
2372 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002373 return false;
2374 }
2375 }
2376 }
2377 }
2378 return true;
2379}
2380
Ian Rogers595799e2012-01-11 17:32:51 -08002381// Returns true if classes referenced by the signature of the method are the
2382// same classes in klass1 as they are in klass2.
2383bool ClassLinker::IsSameMethodSignatureInDifferentClassContexts(const Method* method,
2384 const Class* klass1,
2385 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002386 if (klass1 == klass2) {
2387 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002388 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002389 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002390 const DexFile::ProtoId& proto_id =
2391 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002392 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2393 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002394 if (descriptor == NULL) {
2395 break;
2396 }
2397 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2398 // Found a non-primitive type.
Ian Rogers595799e2012-01-11 17:32:51 -08002399 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002400 return false;
2401 }
2402 }
2403 }
2404 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002405 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002406 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Ian Rogers595799e2012-01-11 17:32:51 -08002407 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002408 return false;
2409 }
2410 }
2411 return true;
2412}
2413
Ian Rogers595799e2012-01-11 17:32:51 -08002414// Returns true if the descriptor resolves to the same class in the context of klass1 and klass2.
2415bool ClassLinker::IsSameDescriptorInDifferentClassContexts(const char* descriptor,
2416 const Class* klass1,
2417 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002418 CHECK(descriptor != NULL);
2419 CHECK(klass1 != NULL);
2420 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002421 if (klass1 == klass2) {
2422 return true;
2423 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002424 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Ian Rogers595799e2012-01-11 17:32:51 -08002425 if (found1 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002426 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002427 }
Ian Rogers595799e2012-01-11 17:32:51 -08002428 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
2429 if (found2 == NULL) {
2430 Thread::Current()->ClearException();
2431 }
2432 return found1 == found2;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002433}
2434
Brian Carlstrom25c33252011-09-18 15:58:35 -07002435bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002436 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002437 if (!klass->IsInterface() && klass->HasSuperClass()) {
2438 Class* super_class = klass->GetSuperClass();
2439 if (super_class->GetStatus() != Class::kStatusInitialized) {
2440 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002441 Thread* self = Thread::Current();
2442 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002443 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002444 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002445 // TODO: check for a pending exception
2446 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002447 if (!can_run_clinit) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002448 // Don't set status to error when we can't run <clinit>.
2449 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing) << PrettyClass(klass);
2450 klass->SetStatus(Class::kStatusVerified);
2451 return false;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002452 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002453 klass->SetStatus(Class::kStatusError);
2454 klass->NotifyAll();
2455 return false;
2456 }
2457 }
2458 }
2459 return true;
2460}
2461
Brian Carlstrom25c33252011-09-18 15:58:35 -07002462bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002463 CHECK(c != NULL);
2464 if (c->IsInitialized()) {
2465 return true;
2466 }
2467
Elliott Hughes5f791332011-09-15 17:45:30 -07002468 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002469 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Ian Rogers595799e2012-01-11 17:32:51 -08002470 bool success = InitializeClass(c, can_run_clinit);
2471 if (!success) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002472 CHECK(self->IsExceptionPending()) << PrettyClass(c);
Ian Rogers595799e2012-01-11 17:32:51 -08002473 }
2474 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002475}
2476
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002477void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002478 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002479 const ClassLoader* cl = c->GetClassLoader();
2480 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002481 ClassDataItemIterator it(dex_file, class_data);
2482 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2483 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002484 }
2485}
2486
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002487void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002488 size_t num_static_fields = klass->NumStaticFields();
2489 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002490 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002491 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002492 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002493 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002494 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002495 return;
2496 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002497 ClassHelper kh(klass);
2498 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002499 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002500 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002501 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002502
Ian Rogers0571d352011-11-03 19:51:38 -07002503 if (it.HasNext()) {
2504 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2505 std::map<uint32_t, Field*> field_map;
2506 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2507 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2508 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002509 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002510 }
2511}
2512
Ian Rogersc2b44472011-12-14 21:17:17 -08002513bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002514 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002515 if (!LinkSuperClass(klass)) {
2516 return false;
2517 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002518 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002519 return false;
2520 }
2521 if (!LinkInstanceFields(klass)) {
2522 return false;
2523 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002524 if (!LinkStaticFields(klass)) {
2525 return false;
2526 }
2527 CreateReferenceInstanceOffsets(klass);
2528 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002529 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2530 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002531 return true;
2532}
2533
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002534bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002535 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002536 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2537 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
Ian Rogerscab01012012-01-10 17:35:46 -08002538 CHECK(class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002539 uint16_t super_class_idx = class_def->superclass_idx_;
2540 if (super_class_idx != DexFile::kDexNoIndex16) {
2541 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002542 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002543 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002544 return false;
2545 }
Ian Rogersbe125a92012-01-11 15:19:49 -08002546 // Verify
2547 if (!klass->CanAccess(super_class)) {
2548 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2549 "Class %s extended by class %s is inaccessible",
2550 PrettyDescriptor(super_class).c_str(),
2551 PrettyDescriptor(klass.get()).c_str());
2552 return false;
2553 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002554 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002555 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002556 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2557 if (interfaces != NULL) {
2558 for (size_t i = 0; i < interfaces->Size(); i++) {
2559 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2560 Class* interface = ResolveType(dex_file, idx, klass.get());
2561 if (interface == NULL) {
2562 DCHECK(Thread::Current()->IsExceptionPending());
2563 return false;
2564 }
2565 // Verify
2566 if (!klass->CanAccess(interface)) {
2567 // TODO: the RI seemed to ignore this in my testing.
2568 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2569 "Interface %s implemented by class %s is inaccessible",
2570 PrettyDescriptor(interface).c_str(),
2571 PrettyDescriptor(klass.get()).c_str());
2572 return false;
2573 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002574 }
2575 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002576 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002577 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002578 return true;
2579}
2580
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002581bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002582 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002583 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002584 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002585 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002586 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002587 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002588 return false;
2589 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002590 return true;
2591 }
2592 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002593 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002594 return false;
2595 }
2596 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002597 if (super->IsFinal() || super->IsInterface()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002598 Thread* self = Thread::Current();
2599 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002600 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002601 PrettyDescriptor(super).c_str(),
2602 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002603 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002604 return false;
2605 }
2606 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002607 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002608 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002609 PrettyDescriptor(super).c_str(),
2610 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002611 return false;
2612 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002613
2614 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2615 if (super->IsFinalizable()) {
2616 klass->SetFinalizable();
2617 }
2618
Elliott Hughes2da50362011-10-10 16:57:08 -07002619 // Inherit reference flags (if any) from the superclass.
2620 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2621 if (reference_flags != 0) {
2622 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2623 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002624 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002625 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002626 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002627 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002628 return false;
2629 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002630
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002631#ifndef NDEBUG
2632 // Ensure super classes are fully resolved prior to resolving fields..
2633 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002634 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002635 super = super->GetSuperClass();
2636 }
2637#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002638 return true;
2639}
2640
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002641// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002642bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002643 if (klass->IsInterface()) {
2644 // No vtable.
2645 size_t count = klass->NumVirtualMethods();
2646 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002647 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002648 return false;
2649 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002650 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002651 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002652 }
jeffhaobdb76512011-09-07 11:43:16 -07002653 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002654 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002655 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002656 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002657 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002658 }
2659 return true;
2660}
2661
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002662bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002663 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002664 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2665 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002666 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002667 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002668 SirtRef<ObjectArray<Method> > vtable(klass->GetSuperClass()->GetVTable()->CopyOf(max_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002669 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002670 MethodHelper local_mh(NULL, this);
2671 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002672 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002673 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002674 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002675 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002676 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002677 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002678 super_mh.ChangeMethod(super_method);
2679 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002680 // Verify
2681 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002682 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002683 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002684 PrettyDescriptor(klass.get()).c_str(),
2685 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002686 return false;
2687 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002688 vtable->Set(j, local_method);
2689 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002690 break;
2691 }
2692 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002693 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002694 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002695 vtable->Set(actual_count, local_method);
2696 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002697 actual_count += 1;
2698 }
2699 }
2700 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002701 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002702 return false;
2703 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002704 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002705 CHECK_LE(actual_count, max_count);
2706 if (actual_count < max_count) {
Ian Rogers30fab402012-01-23 15:43:46 -08002707 vtable.reset(vtable->CopyOf(actual_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002708 }
Ian Rogers30fab402012-01-23 15:43:46 -08002709 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002710 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002711 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002712 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002713 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002714 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002715 return false;
2716 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002717 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002718 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002719 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2720 vtable->Set(i, virtual_method);
2721 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002722 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002723 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002724 }
2725 return true;
2726}
2727
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002728bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002729 size_t super_ifcount;
2730 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002731 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002732 } else {
2733 super_ifcount = 0;
2734 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002735 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002736 ClassHelper kh(klass.get(), this);
2737 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2738 ifcount += num_interfaces;
2739 for (size_t i = 0; i < num_interfaces; i++) {
2740 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2741 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002742 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002743 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002744 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002745 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002746 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002747 return true;
2748 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002749 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002750 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002751 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2752 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogersb52b01a2012-01-12 17:01:38 -08002753 Class* super_interface = super_iftable->Get(i)->GetInterface();
2754 iftable->Set(i, AllocInterfaceEntry(super_interface));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002755 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002756 }
2757 // Flatten the interface inheritance hierarchy.
2758 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002759 for (size_t i = 0; i < num_interfaces; i++) {
2760 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002761 DCHECK(interface != NULL);
2762 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002763 ClassHelper ih(interface);
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002764 Thread* self = Thread::Current();
2765 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002766 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002767 PrettyDescriptor(klass.get()).c_str(),
2768 PrettyDescriptor(ih.GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002769 return false;
2770 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002771 // Check if interface is already in iftable
2772 bool duplicate = false;
2773 for (size_t j = 0; j < idx; j++) {
2774 Class* existing_interface = iftable->Get(j)->GetInterface();
2775 if (existing_interface == interface) {
2776 duplicate = true;
2777 break;
2778 }
2779 }
2780 if (!duplicate) {
2781 // Add this non-duplicate interface.
2782 iftable->Set(idx++, AllocInterfaceEntry(interface));
2783 // Add this interface's non-duplicate super-interfaces.
2784 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2785 Class* super_interface = interface->GetIfTable()->Get(j)->GetInterface();
2786 bool super_duplicate = false;
2787 for (size_t k = 0; k < idx; k++) {
2788 Class* existing_interface = iftable->Get(k)->GetInterface();
2789 if (existing_interface == super_interface) {
2790 super_duplicate = true;
2791 break;
2792 }
2793 }
2794 if (!super_duplicate) {
2795 iftable->Set(idx++, AllocInterfaceEntry(super_interface));
2796 }
2797 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002798 }
2799 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002800 // Shrink iftable in case duplicates were found
2801 if (idx < ifcount) {
2802 iftable.reset(iftable->CopyOf(idx));
2803 ifcount = idx;
2804 } else {
2805 CHECK_EQ(idx, ifcount);
2806 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002807 klass->SetIfTable(iftable.get());
Elliott Hughes4681c802011-09-25 18:04:37 -07002808
2809 // If we're an interface, we don't need the vtable pointers, so we're done.
2810 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002811 return true;
2812 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002813 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002814 MethodHelper vtable_mh(NULL, this);
2815 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002816 for (size_t i = 0; i < ifcount; ++i) {
2817 InterfaceEntry* interface_entry = iftable->Get(i);
2818 Class* interface = interface_entry->GetInterface();
2819 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2820 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002821 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002822 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2823 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002824 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002825 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002826 // For each method listed in the interface's method list, find the
2827 // matching method in our class's method list. We want to favor the
2828 // subclass over the superclass, which just requires walking
2829 // back from the end of the vtable. (This only matters if the
2830 // superclass defines a private method and this class redefines
2831 // it -- otherwise it would use the same vtable slot. In .dex files
2832 // those don't end up in the virtual method table, so it shouldn't
2833 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002834 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2835 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002836 vtable_mh.ChangeMethod(vtable_method);
2837 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002838 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002839 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002840 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002841 return false;
2842 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002843 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002844 break;
2845 }
2846 }
2847 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002848 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002849 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002850 Method* mir_method = miranda_list[mir];
2851 vtable_mh.ChangeMethod(mir_method);
2852 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002853 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002854 break;
2855 }
2856 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002857 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002858 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002859 miranda_method.reset(AllocMethod());
2860 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2861 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002862 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002863 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002864 }
2865 }
2866 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002867 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002868 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002869 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002870 klass->SetVirtualMethods((old_method_count == 0)
2871 ? AllocObjectArray<Method>(new_method_count)
2872 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002873
Ian Rogers30fab402012-01-23 15:43:46 -08002874 SirtRef<ObjectArray<Method> > vtable(klass->GetVTableDuringLinking());
2875 CHECK(vtable.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002876 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002877 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers30fab402012-01-23 15:43:46 -08002878 vtable.reset(vtable->CopyOf(new_vtable_count));
Elliott Hughes4681c802011-09-25 18:04:37 -07002879 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002880 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002881 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002882 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2883 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2884 klass->SetVirtualMethod(old_method_count + i, method);
2885 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002886 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002887 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002888 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002889 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002890
2891 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2892 for (int i = 0; i < vtable->GetLength(); ++i) {
2893 CHECK(vtable->Get(i) != NULL);
2894 }
2895
2896// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2897
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002898 return true;
2899}
2900
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002901bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2902 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002903 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002904}
2905
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002906bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2907 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002908 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002909 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002910 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002911 return success;
2912}
2913
Brian Carlstromdbc05252011-09-09 01:59:59 -07002914struct LinkFieldsComparator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002915 explicit LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002916 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002917 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002918 fh_->ChangeField(field1);
2919 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2920 fh_->ChangeField(field2);
2921 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002922 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2923 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2924 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2925 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002926 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2927 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2928 if (order1 != order2) {
2929 return order1 < order2;
2930 }
2931
2932 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002933 fh_->ChangeField(field1);
2934 StringPiece name1(fh_->GetName());
2935 fh_->ChangeField(field2);
2936 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002937 return name1 < name2;
2938 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002939
2940 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002941};
2942
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002943bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002944 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002945 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002946
2947 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002948 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002949
2950 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002951 size_t size;
2952 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002953 if (is_static) {
2954 size = klass->GetClassSize();
2955 field_offset = Class::FieldsOffset();
2956 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002957 Class* super_class = klass->GetSuperClass();
2958 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002959 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002960 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002961 }
2962 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002963 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002964
Brian Carlstromdbc05252011-09-09 01:59:59 -07002965 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002966
Brian Carlstromdbc05252011-09-09 01:59:59 -07002967 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002968 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002969 std::deque<Field*> grouped_and_sorted_fields;
2970 for (size_t i = 0; i < num_fields; i++) {
2971 grouped_and_sorted_fields.push_back(fields->Get(i));
2972 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002973 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002974 std::sort(grouped_and_sorted_fields.begin(),
2975 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002976 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002977
2978 // References should be at the front.
2979 size_t current_field = 0;
2980 size_t num_reference_fields = 0;
2981 for (; current_field < num_fields; current_field++) {
2982 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002983 fh.ChangeField(field);
2984 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002985 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002986 if (isPrimitive) {
2987 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002988 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002989 grouped_and_sorted_fields.pop_front();
2990 num_reference_fields++;
2991 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002992 field->SetOffset(field_offset);
2993 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002994 }
2995
2996 // Now we want to pack all of the double-wide fields together. If
2997 // we're not aligned, though, we want to shuffle one 32-bit field
2998 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002999 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003000 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
3001 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003002 fh.ChangeField(field);
3003 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003004 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
3005 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003006 continue;
3007 }
3008 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003009 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003010 // drop the consumed field
3011 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
3012 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003013 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07003014 // whether we found a 32-bit field for padding or not, we advance
3015 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003016 }
3017
3018 // Alignment is good, shuffle any double-wide fields forward, and
3019 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07003020 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07003021 while (!grouped_and_sorted_fields.empty()) {
3022 Field* field = grouped_and_sorted_fields.front();
3023 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003024 fh.ChangeField(field);
3025 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003026 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07003027 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003028 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003029 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003030 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07003031 ? sizeof(uint64_t)
3032 : sizeof(uint32_t)));
3033 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003034 }
3035
Elliott Hughesadb460d2011-10-05 17:02:34 -07003036 // 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 -08003037 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
3038 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07003039 // We know there are no non-reference fields in the Reference classes, and we know
3040 // that 'referent' is alphabetically last, so this is easy...
3041 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003042 fh.ChangeField(fields->Get(num_fields - 1));
Elliott Hughesba8eee12012-01-24 20:25:24 -08003043 CHECK_STREQ(fh.GetName(), "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07003044 --num_reference_fields;
3045 }
3046
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003047#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07003048 // Make sure that all reference fields appear before
3049 // non-reference fields, and all double-wide fields are aligned.
3050 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07003051 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003052 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003053 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003054 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003055 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07003056 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07003057 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
3058 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003059 fh.ChangeField(field);
3060 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003061 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003062 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07003063 is_primitive = true; // We lied above, so we have to expect a lie here.
3064 }
3065 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07003066 if (!seen_non_ref) {
3067 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003068 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003069 }
Brian Carlstrombe977852011-07-19 14:54:54 -07003070 } else {
3071 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003072 }
3073 }
Brian Carlstrombe977852011-07-19 14:54:54 -07003074 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003075 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003076 }
3077#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003078 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003079 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003080 if (is_static) {
3081 klass->SetNumReferenceStaticFields(num_reference_fields);
3082 klass->SetClassSize(size);
3083 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003084 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003085 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003086 klass->SetObjectSize(size);
3087 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003088 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003089 return true;
3090}
3091
3092// Set the bitmap of reference offsets, refOffsets, from the ifields
3093// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003094void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003095 uint32_t reference_offsets = 0;
3096 Class* super_class = klass->GetSuperClass();
3097 if (super_class != NULL) {
3098 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003099 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003100 if (reference_offsets == CLASS_WALK_SUPER) {
3101 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003102 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003103 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003104 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003105 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003106}
3107
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003108void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003109 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003110}
3111
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003112void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003113 uint32_t reference_offsets) {
3114 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003115 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
3116 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003117 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003118 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003119 // All of the fields that contain object references are guaranteed
3120 // to be at the beginning of the fields list.
3121 for (size_t i = 0; i < num_reference_fields; ++i) {
3122 // Note that byte_offset is the offset from the beginning of
3123 // object, not the offset into instance data
3124 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003125 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003126 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
3127 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
3128 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07003129 CHECK_NE(new_bit, 0U);
3130 reference_offsets |= new_bit;
3131 } else {
3132 reference_offsets = CLASS_WALK_SUPER;
3133 break;
3134 }
3135 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003136 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003137 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003138 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003139 } else {
3140 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003141 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003142}
3143
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003144String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07003145 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003146 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003147 if (resolved != NULL) {
3148 return resolved;
3149 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003150 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
3151 int32_t utf16_length = dex_file.GetStringLength(string_id);
3152 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07003153 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003154 dex_cache->SetResolvedString(string_idx, string);
3155 return string;
3156}
3157
3158Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003159 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003160 DexCache* dex_cache,
3161 const ClassLoader* class_loader) {
3162 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003163 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07003164 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003165 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003166 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05003167 // TODO: we used to throw here if resolved's class loader was not the
3168 // boot class loader. This was to permit different classes with the
3169 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003170 dex_cache->SetResolvedType(type_idx, resolved);
3171 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08003172 CHECK(Thread::Current()->IsExceptionPending())
3173 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003174 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003175 }
3176 return resolved;
3177}
3178
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003179Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
3180 uint32_t method_idx,
3181 DexCache* dex_cache,
3182 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003183 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003184 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
3185 if (resolved != NULL) {
3186 return resolved;
3187 }
3188 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3189 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
3190 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07003191 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003192 return NULL;
3193 }
3194
Ian Rogers0571d352011-11-03 19:51:38 -07003195 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
3196 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003197 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003198 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003199 } else if (klass->IsInterface()) {
3200 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003201 } else {
3202 resolved = klass->FindVirtualMethod(name, signature);
3203 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003204 if (resolved != NULL) {
3205 dex_cache->SetResolvedMethod(method_idx, resolved);
3206 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003207 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003208 }
3209 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003210}
3211
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003212Field* ClassLinker::ResolveField(const DexFile& dex_file,
3213 uint32_t field_idx,
3214 DexCache* dex_cache,
3215 const ClassLoader* class_loader,
3216 bool is_static) {
3217 Field* resolved = dex_cache->GetResolvedField(field_idx);
3218 if (resolved != NULL) {
3219 return resolved;
3220 }
3221 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3222 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3223 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003224 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003225 return NULL;
3226 }
3227
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003228 const char* name = dex_file.GetFieldName(field_id);
3229 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003230 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003231 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003232 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003233 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003234 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003235 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003236 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003237 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08003238 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
3239 }
3240 return resolved;
3241}
3242
3243Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
3244 uint32_t field_idx,
3245 DexCache* dex_cache,
3246 const ClassLoader* class_loader) {
3247 Field* resolved = dex_cache->GetResolvedField(field_idx);
3248 if (resolved != NULL) {
3249 return resolved;
3250 }
3251 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3252 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3253 if (klass == NULL) {
3254 DCHECK(Thread::Current()->IsExceptionPending());
3255 return NULL;
3256 }
3257
3258 const char* name = dex_file.GetFieldName(field_id);
3259 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3260 resolved = klass->FindField(name, type);
3261 if (resolved != NULL) {
3262 dex_cache->SetResolvedField(field_idx, resolved);
3263 } else {
3264 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003265 }
3266 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07003267}
3268
Ian Rogersad25ac52011-10-04 19:13:33 -07003269const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
3270 Class* declaring_class = referrer->GetDeclaringClass();
3271 DexCache* dex_cache = declaring_class->GetDexCache();
3272 const DexFile& dex_file = FindDexFile(dex_cache);
3273 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3274 return dex_file.GetShorty(method_id.proto_idx_);
3275}
3276
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003277void ClassLinker::DumpAllClasses(int flags) const {
3278 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3279 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3280 std::vector<Class*> all_classes;
3281 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003282 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003283 typedef Table::const_iterator It; // TODO: C++0x auto
3284 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3285 all_classes.push_back(it->second);
3286 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003287 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3288 all_classes.push_back(it->second);
3289 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003290 }
3291
3292 for (size_t i = 0; i < all_classes.size(); ++i) {
3293 all_classes[i]->DumpClass(std::cerr, flags);
3294 }
3295}
3296
Elliott Hughescac6cc72011-11-03 20:31:21 -07003297void ClassLinker::DumpForSigQuit(std::ostream& os) const {
3298 MutexLock mu(classes_lock_);
3299 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3300 << classes_.size() << " allocated classes\n";
3301}
3302
Elliott Hughese27955c2011-08-26 15:21:24 -07003303size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003304 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003305 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003306}
3307
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003308pid_t ClassLinker::GetClassesLockOwner() {
3309 return classes_lock_.GetOwner();
3310}
3311
3312pid_t ClassLinker::GetDexLockOwner() {
3313 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003314}
3315
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003316void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3317 DCHECK(!init_done_);
3318
3319 DCHECK(klass != NULL);
3320 DCHECK(klass->GetClassLoader() == NULL);
3321
3322 DCHECK(class_roots_ != NULL);
3323 DCHECK(class_roots_->Get(class_root) == NULL);
3324 class_roots_->Set(class_root, klass);
3325}
3326
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003327} // namespace art