blob: d8bf6642d5450b625be6456a950080317a981c66 [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
Brian Carlstroma004aa92012-02-08 18:05:09 -0800212ClassLinker* ClassLinker::CreateFromCompiler(const std::vector<const DexFile*>& boot_class_path,
213 InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700214 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800215 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800216 class_linker->InitFromCompiler(boot_class_path);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700217 return class_linker.release();
218}
219
Brian Carlstroma004aa92012-02-08 18:05:09 -0800220ClassLinker* ClassLinker::CreateFromImage(InternTable* intern_table) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800221 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700222 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700223 return class_linker.release();
224}
225
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800226ClassLinker::ClassLinker(InternTable* intern_table)
227 : dex_lock_("ClassLinker dex lock"),
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700228 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700229 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700230 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700231 init_done_(false),
232 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700233 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700234}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700235
Brian Carlstroma004aa92012-02-08 18:05:09 -0800236void ClassLinker::InitFromCompiler(const std::vector<const DexFile*>& boot_class_path) {
237 VLOG(startup) << "ClassLinker::Init";
238 CHECK(Runtime::Current()->IsCompiler());
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700239
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700240 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700241
Elliott Hughes30646832011-10-13 16:59:46 -0700242 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700243 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
244 CHECK(java_lang_Class.get() != NULL);
245 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700246 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700247 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700248
Elliott Hughes418d20f2011-09-22 14:00:39 -0700249 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700250 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
251 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700252
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700253 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700254 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
255 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700256 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700257 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700258 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700259
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700260 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700261 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
262 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700263
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700264 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700265 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700266
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700267 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700268 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
269 char_array_class->SetComponentType(char_class.get());
270 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700271
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700272 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700273 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
274 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700275 java_lang_String->SetObjectSize(sizeof(String));
276 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400277
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700278 // Create storage for root classes, save away our work so far (requires
279 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700280 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700281 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700282 SetClassRoot(kJavaLangClass, java_lang_Class.get());
283 SetClassRoot(kJavaLangObject, java_lang_Object.get());
284 SetClassRoot(kClassArrayClass, class_array_class.get());
285 SetClassRoot(kObjectArrayClass, object_array_class.get());
286 SetClassRoot(kCharArrayClass, char_array_class.get());
287 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700288
289 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700290 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
291 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
292 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
293 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
294 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
295 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
296 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
297 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700298
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700299 // Create array interface entries to populate once we can load system classes
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700300 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700301
302 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700303 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700304 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700305 IntArray::SetArrayClass(int_array_class.get());
306 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700307
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700308 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700309
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700310 // setup boot_class_path_ and register class_path now that we can
311 // use AllocObjectArray to create DexCache instances
Brian Carlstroma004aa92012-02-08 18:05:09 -0800312 CHECK_NE(0U, boot_class_path.size());
313 for (size_t i = 0; i != boot_class_path.size(); ++i) {
314 const DexFile* dex_file = boot_class_path[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700315 CHECK(dex_file != NULL);
316 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700317 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700318
Elliott Hughes80609252011-09-23 17:24:51 -0700319 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700320 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700321 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700322 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700323 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700324 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
325
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700326 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
327 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700328 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700329 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700330 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700331 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700332
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700333 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700334 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700335 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700336 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700337 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700338 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700339
340 // now we can use FindSystemClass
341
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700342 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700343 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700344 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700345
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700346 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700347 java_lang_Object->SetStatus(Class::kStatusNotReady);
348 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700349 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700350 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
351 java_lang_String->SetStatus(Class::kStatusNotReady);
352 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700353 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700354 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
355
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700356 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700357 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
358 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
359
360 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
361 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
362
363 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700364 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700365
366 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
367 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
368
369 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700370 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700371
372 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
373 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
374
375 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
376 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
377
378 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
379 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
380
Elliott Hughes418d20f2011-09-22 14:00:39 -0700381 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700382 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700383
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700384 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700385 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700386
387 // Setup the single, global copies of "interfaces" and "iftable"
388 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
389 CHECK(java_lang_Cloneable != NULL);
390 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
391 CHECK(java_io_Serializable != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700392 // We assume that Cloneable/Serializable don't have superinterfaces --
393 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700394 // supers as well.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800395 array_iftable_->Set(0, AllocInterfaceEntry(java_lang_Cloneable));
396 array_iftable_->Set(1, AllocInterfaceEntry(java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700397
Elliott Hughes418d20f2011-09-22 14:00:39 -0700398 // Sanity check Class[] and Object[]'s interfaces
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800399 ClassHelper kh(class_array_class.get(), this);
400 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
401 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
402 kh.ChangeClass(object_array_class.get());
403 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
404 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
Elliott Hughes80609252011-09-23 17:24:51 -0700405 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700406 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700407 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700408 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700409
Elliott Hughes80609252011-09-23 17:24:51 -0700410 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
411 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700412 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700413
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700414 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700415 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700416 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700417
418 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700419 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700420 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700421
Ian Rogers466bb252011-10-14 03:29:56 -0700422 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
423
424 // Create java.lang.reflect.Proxy root
425 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
426 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
427
Brian Carlstrom1f870082011-08-23 16:02:11 -0700428 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700429 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
430 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700431 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700432 java_lang_ref_FinalizerReference->SetAccessFlags(
433 java_lang_ref_FinalizerReference->GetAccessFlags() |
434 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700435 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700436 java_lang_ref_PhantomReference->SetAccessFlags(
437 java_lang_ref_PhantomReference->GetAccessFlags() |
438 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700439 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700440 java_lang_ref_SoftReference->SetAccessFlags(
441 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700442 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700443 java_lang_ref_WeakReference->SetAccessFlags(
444 java_lang_ref_WeakReference->GetAccessFlags() |
445 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700446
Brian Carlstromaded5f72011-10-07 17:15:04 -0700447 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700448 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700449 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700450 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
451
452 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
453 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
454 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
455
456 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
457 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
458 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
459 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
460
Ian Rogers5167c972012-02-03 10:41:20 -0800461 // Set up java.lang.Throwable and java.lang.StackTraceElement as a convenience
462 SetClassRoot(kJavaLangThrowable, FindSystemClass("Ljava/lang/Throwable;"));
463 Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700464 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
465 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700466 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700467
Brian Carlstroma663ea52011-08-19 23:33:41 -0700468 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700469
Brian Carlstroma004aa92012-02-08 18:05:09 -0800470 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700471}
472
473void ClassLinker::FinishInit() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800474 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700475
476 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700477 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700478 // as the types of the field can't be resolved prior to the runtime being
479 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700480 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700481 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700482 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
483
Elliott Hughesadb460d2011-10-05 17:02:34 -0700484 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
485
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800486 const DexFile& java_lang_dex = FindDexFile(java_lang_ref_Reference->GetDexCache());
487
Brian Carlstrom16192862011-09-12 17:50:06 -0700488 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800489 FieldHelper fh(pendingNext, this);
490 CHECK_STREQ(fh.GetName(), "pendingNext");
491 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
492 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700493
494 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800495 fh.ChangeField(queue);
496 CHECK_STREQ(fh.GetName(), "queue");
497 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
498 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700499
500 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800501 fh.ChangeField(queueNext);
502 CHECK_STREQ(fh.GetName(), "queueNext");
503 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
504 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700505
506 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800507 fh.ChangeField(referent);
508 CHECK_STREQ(fh.GetName(), "referent");
509 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
510 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700511
512 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800513 fh.ChangeField(zombie);
514 CHECK_STREQ(fh.GetName(), "zombie");
515 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
516 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700517
518 Heap::SetReferenceOffsets(referent->GetOffset(),
519 queue->GetOffset(),
520 queueNext->GetOffset(),
521 pendingNext->GetOffset(),
522 zombie->GetOffset());
523
Brian Carlstroma663ea52011-08-19 23:33:41 -0700524 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700525 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700526 ClassRoot class_root = static_cast<ClassRoot>(i);
527 Class* klass = GetClassRoot(class_root);
528 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700529 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700530 // note SetClassRoot does additional validation.
531 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700532 }
533
Elliott Hughes92f14b22011-10-06 12:29:54 -0700534 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700535
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700536 // disable the slow paths in FindClass and CreatePrimitiveClass now
537 // that Object, Class, and Object[] are setup
538 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700539
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800540 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700541}
542
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700543void ClassLinker::RunRootClinits() {
544 Thread* self = Thread::Current();
545 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
546 Class* c = GetClassRoot(ClassRoot(i));
547 if (!c->IsArrayClass() && !c->IsPrimitive()) {
548 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700549 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700550 }
551 }
552}
553
Brian Carlstromd601af82012-01-06 10:15:19 -0800554bool ClassLinker::GenerateOatFile(const std::string& dex_filename,
555 int oat_fd,
556 const std::string& oat_cache_filename) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800557 std::string dex2oat_string(GetAndroidRoot());
558 dex2oat_string += "/bin/dex2oat";
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800559#ifndef NDEBUG
560 dex2oat_string += 'd';
561#endif
562 const char* dex2oat = dex2oat_string.c_str();
563
Brian Carlstroma004aa92012-02-08 18:05:09 -0800564 const char* class_path = Runtime::Current()->GetClassPathString().c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800565
566 std::string boot_image_option_string("--boot-image=");
Ian Rogers30fab402012-01-23 15:43:46 -0800567 boot_image_option_string += Heap::GetSpaces()[0]->AsImageSpace()->GetImageFilename();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800568 const char* boot_image_option = boot_image_option_string.c_str();
569
570 std::string dex_file_option_string("--dex-file=");
Brian Carlstromd601af82012-01-06 10:15:19 -0800571 dex_file_option_string += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800572 const char* dex_file_option = dex_file_option_string.c_str();
573
Brian Carlstromd601af82012-01-06 10:15:19 -0800574 std::string oat_fd_option_string("--oat-fd=");
Brian Carlstrom866c8622012-01-06 16:35:13 -0800575 StringAppendF(&oat_fd_option_string, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800576 const char* oat_fd_option = oat_fd_option_string.c_str();
577
Brian Carlstroma004aa92012-02-08 18:05:09 -0800578 std::string oat_location_option_string("--oat-location=");
579 oat_location_option_string += oat_cache_filename;
580 const char* oat_location_option = oat_location_option_string.c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800581
jeffhao262bf462011-10-20 18:36:32 -0700582 // fork and exec dex2oat
583 pid_t pid = fork();
584 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800585 // no allocation allowed between fork and exec
Ian Rogers725aee52012-01-11 11:56:56 -0800586
587 // change process groups, so we don't get reaped by ProcessManager
588 setpgid(0, 0);
589
jeffhao10037c82012-01-23 15:06:23 -0800590 VLOG(class_linker) << dex2oat
591 << " --runtime-arg -Xms64m"
592 << " --runtime-arg -Xmx64m"
593 << " --runtime-arg -classpath"
594 << " --runtime-arg " << class_path
595 << " " << boot_image_option
596 << " " << dex_file_option
597 << " " << oat_fd_option
Brian Carlstroma004aa92012-02-08 18:05:09 -0800598 << " " << oat_location_option;
jeffhao10037c82012-01-23 15:06:23 -0800599
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800600 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700601 "--runtime-arg", "-Xms64m",
602 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500603 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800604 "--runtime-arg", class_path,
605 boot_image_option,
606 dex_file_option,
Brian Carlstromd601af82012-01-06 10:15:19 -0800607 oat_fd_option,
Brian Carlstroma004aa92012-02-08 18:05:09 -0800608 oat_location_option,
jeffhao262bf462011-10-20 18:36:32 -0700609 NULL);
610
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800611 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
Brian Carlstromd601af82012-01-06 10:15:19 -0800612 return false;
jeffhao262bf462011-10-20 18:36:32 -0700613 } else {
614 // wait for dex2oat to finish
615 int status;
616 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
617 if (got_pid != pid) {
618 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
Brian Carlstromd601af82012-01-06 10:15:19 -0800619 return false;
jeffhao262bf462011-10-20 18:36:32 -0700620 }
621 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800622 LOG(ERROR) << dex2oat << " failed with dex-file=" << dex_filename;
623 return false;
jeffhao262bf462011-10-20 18:36:32 -0700624 }
625 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800626 return true;
jeffhao262bf462011-10-20 18:36:32 -0700627}
628
Brian Carlstrom866c8622012-01-06 16:35:13 -0800629void ClassLinker::RegisterOatFile(const OatFile& oat_file) {
630 MutexLock mu(dex_lock_);
631 RegisterOatFileLocked(oat_file);
632}
633
634void ClassLinker::RegisterOatFileLocked(const OatFile& oat_file) {
635 dex_lock_.AssertHeld();
636 oat_files_.push_back(&oat_file);
637}
638
Ian Rogers30fab402012-01-23 15:43:46 -0800639OatFile* ClassLinker::OpenOat(const ImageSpace* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700640 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700641 const Runtime* runtime = Runtime::Current();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700642 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800643 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
644 // check the down cast
645 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700646 std::string oat_filename;
647 oat_filename += runtime->GetHostPrefix();
648 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma004aa92012-02-08 18:05:09 -0800649 OatFile* oat_file = OatFile::Open(oat_filename, oat_filename, image_header.GetOatBegin());
Ian Rogers30fab402012-01-23 15:43:46 -0800650 VLOG(startup) << "ClassLinker::OpenOat entering oat_filename=" << oat_filename;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700651 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700652 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700653 return NULL;
654 }
655 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
656 uint32_t image_oat_checksum = image_header.GetOatChecksum();
657 if (oat_checksum != image_oat_checksum) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800658 LOG(ERROR) << "Failed to match oat file checksum " << std::hex << oat_checksum
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700659 << " to expected oat checksum " << std::hex << oat_checksum
660 << " in image";
661 return NULL;
662 }
Brian Carlstrom866c8622012-01-06 16:35:13 -0800663 RegisterOatFileLocked(*oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800664 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700665 return oat_file;
666}
667
Brian Carlstromae826982011-11-09 01:33:42 -0800668const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800669 return FindOpenedOatFileFromDexLocation(dex_file.GetLocation());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800670}
671
Brian Carlstroma004aa92012-02-08 18:05:09 -0800672const OatFile* ClassLinker::FindOpenedOatFileFromDexLocation(const std::string& dex_location) {
Brian Carlstromae826982011-11-09 01:33:42 -0800673 for (size_t i = 0; i < oat_files_.size(); i++) {
674 const OatFile* oat_file = oat_files_[i];
675 DCHECK(oat_file != NULL);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800676 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, false);
Brian Carlstroma004aa92012-02-08 18:05:09 -0800677 if (oat_dex_file != NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800678 return oat_file;
679 }
680 }
681 return NULL;
682}
683
Brian Carlstromd601af82012-01-06 10:15:19 -0800684class LockedFd {
685 public:
686 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
687 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
688 if (fd == -1) {
689 PLOG(ERROR) << "Failed to open file '" << name << "'";
690 return NULL;
691 }
692 fchmod(fd, mode);
693
694 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
695 // try to lock non-blocking so we can log if we need may need to block
696 int result = flock(fd, LOCK_EX | LOCK_NB);
697 if (result == -1) {
698 LOG(WARNING) << "sleeping while locking file " << name;
699 // retry blocking
700 result = flock(fd, LOCK_EX);
701 }
702 if (result == -1) {
703 PLOG(ERROR) << "Failed to lock file '" << name << "'";
704 close(fd);
705 return NULL;
706 }
707 return new LockedFd(fd);
708 }
709
710 int GetFd() const {
711 return fd_;
712 }
713
714 ~LockedFd() {
715 if (fd_ != -1) {
716 int result = flock(fd_, LOCK_UN);
717 if (result == -1) {
718 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
719 }
720 close(fd_);
721 }
722 }
723
724 private:
725 explicit LockedFd(int fd) : fd_(fd) {}
726
727 int fd_;
728};
729
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800730static const DexFile* FindDexFileInOatLocation(const std::string& dex_location,
731 uint32_t dex_location_checksum,
732 const std::string& oat_location) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800733 UniquePtr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, NULL));
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800734 if (oat_file.get() == NULL) {
735 return NULL;
736 }
737 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
738 if (oat_dex_file == NULL) {
739 return NULL;
740 }
741 if (oat_dex_file->GetDexFileLocationChecksum() != dex_location_checksum) {
742 return NULL;
743 }
744 Runtime::Current()->GetClassLinker()->RegisterOatFile(*oat_file.release());
745 return oat_dex_file->OpenDexFile();
746}
747
748const DexFile* ClassLinker::FindOrCreateOatFileForDexLocation(const std::string& dex_location,
749 const std::string& oat_location) {
750 uint32_t dex_location_checksum;
751 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) {
752 LOG(ERROR) << "Failed to compute checksum '" << dex_location << "'";
753 return NULL;
754 }
755
756 // Check if we already have an up-to-date output file
757 const DexFile* dex_file = FindDexFileInOatLocation(dex_location,
758 dex_location_checksum,
759 oat_location);
760 if (dex_file != NULL) {
761 return dex_file;
762 }
763
764 // Generate the output oat file for the dex file
765 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
766 UniquePtr<File> file(OS::OpenFile(oat_location.c_str(), true));
767 if (file.get() == NULL) {
768 LOG(ERROR) << "Failed to create oat file: " << oat_location;
769 return NULL;
770 }
771 if (!class_linker->GenerateOatFile(dex_location, file->Fd(), oat_location)) {
772 LOG(ERROR) << "Failed to generate oat file: " << oat_location;
773 return NULL;
774 }
775 // Open the oat from file descriptor we passed to GenerateOatFile
776 if (lseek(file->Fd(), 0, SEEK_SET) != 0) {
777 LOG(ERROR) << "Failed to seek to start of generated oat file: " << oat_location;
778 return NULL;
779 }
780 const OatFile* oat_file = OatFile::Open(*file.get(), oat_location, NULL);
781 if (oat_file == NULL) {
782 LOG(ERROR) << "Failed to open generated oat file: " << oat_location;
783 return NULL;
784 }
785 class_linker->RegisterOatFile(*oat_file);
786 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
787 if (oat_dex_file == NULL) {
788 LOG(ERROR) << "Failed to find dex file in generated oat file: " << oat_location;
789 return NULL;
790 }
791 return oat_dex_file->OpenDexFile();
792}
793
794const DexFile* ClassLinker::FindDexFileInOatFileFromDexLocation(const std::string& dex_location) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700795 MutexLock mu(dex_lock_);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800796
Brian Carlstroma004aa92012-02-08 18:05:09 -0800797 const OatFile* open_oat_file = FindOpenedOatFileFromDexLocation(dex_location);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800798 if (open_oat_file != NULL) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800799 return open_oat_file->GetOatDexFile(dex_location)->OpenDexFile();
Brian Carlstromae826982011-11-09 01:33:42 -0800800 }
801
Brian Carlstroma004aa92012-02-08 18:05:09 -0800802 // Look for an existing file next to dex, assuming its up-to-date if found
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800803 std::string oat_filename(OatFile::DexFilenameToOatFilename(dex_location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800804 const OatFile* oat_file = FindOatFileFromOatLocation(oat_filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800805 if (oat_file != NULL) {
806 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
Brian Carlstroma004aa92012-02-08 18:05:09 -0800807 CHECK(oat_dex_file != NULL) << oat_filename << " " << dex_location;
808 return oat_dex_file->OpenDexFile();
809 }
810 // Look for an existing file in the art-cache, validating the result if found
811 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
812 std::string cache_location(GetArtCacheFilenameOrDie(oat_filename));
813 oat_file = FindOatFileFromOatLocation(cache_location);
814 if (oat_file != NULL) {
815 uint32_t dex_location_checksum;
816 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) {
817 LOG(WARNING) << "Failed to compute checksum: " << dex_location;
818 return NULL;
819 }
820 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
821 CHECK(oat_dex_file != NULL) << oat_filename << " " << dex_location;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800822 if (dex_location_checksum == oat_dex_file->GetDexFileLocationChecksum()) {
823 return oat_file->GetOatDexFile(dex_location)->OpenDexFile();
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700824 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800825 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
826 << " checksum ( " << std::hex << oat_dex_file->GetDexFileLocationChecksum()
827 << ") mismatch with " << dex_location
828 << " (" << std::hex << dex_location_checksum << ")--- regenerating";
829 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
830 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
Brian Carlstromd601af82012-01-06 10:15:19 -0800831 }
jeffhao262bf462011-10-20 18:36:32 -0700832 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800833 LOG(INFO) << "Failed to open oat file from " << oat_filename << " or " << cache_location << ".";
834
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800835 // Try to generate oat file if it wasn't found or was obsolete.
836 std::string oat_cache_filename(GetArtCacheFilenameOrDie(oat_filename));
837 return FindOrCreateOatFileForDexLocation(dex_location, oat_cache_filename);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700838}
839
Brian Carlstromae826982011-11-09 01:33:42 -0800840const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700841 for (size_t i = 0; i < oat_files_.size(); i++) {
842 const OatFile* oat_file = oat_files_[i];
843 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800844 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700845 return oat_file;
846 }
847 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700848 return NULL;
849}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700850
Brian Carlstromae826982011-11-09 01:33:42 -0800851const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
jeffhaof6174e82012-01-31 16:14:17 -0800852 MutexLock mu(dex_lock_);
853 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
854 if (oat_file != NULL) {
855 return oat_file;
856 }
857
Brian Carlstroma004aa92012-02-08 18:05:09 -0800858 oat_file = OatFile::Open(oat_location, oat_location, NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700859 if (oat_file == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800860 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700861 }
Brian Carlstromae826982011-11-09 01:33:42 -0800862 CHECK(oat_file != NULL) << oat_location;
jeffhaof6174e82012-01-31 16:14:17 -0800863 RegisterOatFileLocked(*oat_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700864 return oat_file;
865}
866
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700867void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800868 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700869 CHECK(!init_done_);
870
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700871 const std::vector<Space*>& spaces = Heap::GetSpaces();
872 for (size_t i = 0; i < spaces.size(); i++) {
Ian Rogers30fab402012-01-23 15:43:46 -0800873 if (spaces[i]->IsImageSpace()) {
874 ImageSpace* space = spaces[i]->AsImageSpace();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700875 OatFile* oat_file = OpenOat(space);
876 CHECK(oat_file != NULL) << "Failed to open oat file for image";
877 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
878 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
879
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800880 if (i == 0) {
881 // Special case of setting up the String class early so that we can test arbitrary objects
882 // as being Strings or not
Ian Rogers30fab402012-01-23 15:43:46 -0800883 Class* java_lang_String = space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800884 ->AsObjectArray<Class>()->Get(kJavaLangString);
885 String::SetClass(java_lang_String);
886 }
887
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700888 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
889 static_cast<uint32_t>(dex_caches->GetLength()));
890 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700891 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800892 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom89521892011-12-07 22:05:07 -0800893 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
894 const DexFile* dex_file = oat_dex_file->OpenDexFile();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700895 if (dex_file == NULL) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800896 LOG(FATAL) << "Failed to open dex file " << dex_file_location
897 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700898 }
899
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800900 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700901
Brian Carlstromdf143242011-10-10 18:05:34 -0700902 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700903 }
904 }
905 }
906
Brian Carlstroma663ea52011-08-19 23:33:41 -0700907 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
908 DCHECK(heap_bitmap != NULL);
909
Brian Carlstroma663ea52011-08-19 23:33:41 -0700910 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700911 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700912
913 // reinit class_roots_
Ian Rogers30fab402012-01-23 15:43:46 -0800914 Object* class_roots_object =
915 spaces[0]->AsImageSpace()->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700916 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700917
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800918 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700919 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
920 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800921 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700922 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700923 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700924 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
925 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
926 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
927 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
928 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
929 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
930 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
931 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700932 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Ian Rogers5167c972012-02-03 10:41:20 -0800933 Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700934 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700935
936 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700937
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800938 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700939}
940
Brian Carlstrom78128a62011-09-15 17:21:19 -0700941void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700942 DCHECK(obj != NULL);
943 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700944 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700945
Elliott Hughesdbb40792011-11-18 17:05:22 -0800946 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700947 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700948 return;
949 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700950 if (obj->IsClass()) {
951 // restore class to ClassLinker::classes_ table
952 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800953 ClassHelper kh(klass, class_linker);
Brian Carlstrom07bb8552012-01-18 22:10:50 -0800954 Class* existing = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
955 DCHECK(existing == NULL) << kh.GetDescriptor();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700956 return;
957 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700958}
959
960// Keep in sync with InitCallback. Anything we visit, we need to
961// reinit references to when reinitializing a ClassLinker from a
962// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700963void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
964 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700965
966 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700967 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700968 }
969
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700970 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700971 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700972 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700973 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700974 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700975 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700976 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700977 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700978
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700979 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700980}
981
Elliott Hughesa2155262011-11-16 16:26:58 -0800982void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
983 MutexLock mu(classes_lock_);
984 typedef Table::const_iterator It; // TODO: C++0x auto
985 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
986 if (!visitor(it->second, arg)) {
987 return;
988 }
989 }
990 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
991 if (!visitor(it->second, arg)) {
992 return;
993 }
994 }
995}
996
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700997ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700998 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700999 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -07001000 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001001 BooleanArray::ResetArrayClass();
1002 ByteArray::ResetArrayClass();
1003 CharArray::ResetArrayClass();
1004 DoubleArray::ResetArrayClass();
1005 FloatArray::ResetArrayClass();
1006 IntArray::ResetArrayClass();
1007 LongArray::ResetArrayClass();
1008 ShortArray::ResetArrayClass();
1009 PathClassLoader::ResetClass();
Ian Rogers5167c972012-02-03 10:41:20 -08001010 Throwable::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001011 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001012 STLDeleteElements(&boot_class_path_);
1013 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001014}
1015
1016DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001017 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
1018 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001019 return NULL;
1020 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001021 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
1022 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001023 return NULL;
1024 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001025 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
1026 if (strings.get() == NULL) {
1027 return NULL;
1028 }
1029 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
1030 if (types.get() == NULL) {
1031 return NULL;
1032 }
1033 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
1034 if (methods.get() == NULL) {
1035 return NULL;
1036 }
1037 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
1038 if (fields.get() == NULL) {
1039 return NULL;
1040 }
1041 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
1042 if (code_and_direct_methods.get() == NULL) {
1043 return NULL;
1044 }
1045 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
1046 if (initialized_static_storage.get() == NULL) {
1047 return NULL;
1048 }
1049
1050 dex_cache->Init(location.get(),
1051 strings.get(),
1052 types.get(),
1053 methods.get(),
1054 fields.get(),
1055 code_and_direct_methods.get(),
1056 initialized_static_storage.get());
1057 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001058}
1059
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001060CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
1061 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -07001062}
1063
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001064InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
1065 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001066 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
1067 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001068 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001069 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001070}
1071
Brian Carlstrom4873d462011-08-21 15:23:39 -07001072Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
1073 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001074 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001075 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001076 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001077 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001078}
1079
Brian Carlstrom4873d462011-08-21 15:23:39 -07001080Class* ClassLinker::AllocClass(size_t class_size) {
1081 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001082}
1083
Jesse Wilson35baaab2011-08-10 16:18:03 -04001084Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001085 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -07001086}
1087
1088Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001089 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001090}
1091
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001092ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
1093 return ObjectArray<StackTraceElement>::Alloc(
1094 GetClassRoot(kJavaLangStackTraceElementArrayClass),
1095 length);
1096}
1097
Brian Carlstromaded5f72011-10-07 17:15:04 -07001098Class* EnsureResolved(Class* klass) {
1099 DCHECK(klass != NULL);
1100 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -07001101 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001102 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001103 ObjectLock lock(klass);
1104 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001105 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001106 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001107 PrettyDescriptor(klass).c_str());
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001108 klass->SetStatus(Class::kStatusError);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001109 return NULL;
1110 }
1111 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001112 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001113 lock.Wait();
1114 }
1115 }
1116 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001117 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001118 return NULL;
1119 }
1120 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001121 CHECK(klass->IsResolved()) << PrettyClass(klass);
1122 CHECK(!self->IsExceptionPending())
1123 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
1124 return klass;
1125}
1126
Elliott Hughesdb7d5e92011-12-16 18:47:37 -08001127Class* ClassLinker::FindSystemClass(const char* descriptor) {
1128 return FindClass(descriptor, NULL);
1129}
1130
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001131Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001132 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001133 Thread* self = Thread::Current();
1134 DCHECK(self != NULL);
1135 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001136 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001137 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1138 // for primitive classes that aren't backed by dex files.
1139 return FindPrimitiveClass(descriptor[0]);
1140 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001141 // Find the class in the loaded classes table.
1142 Class* klass = LookupClass(descriptor, class_loader);
1143 if (klass != NULL) {
1144 return EnsureResolved(klass);
1145 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001146 // Class is not yet loaded.
1147 if (descriptor[0] == '[') {
1148 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001149
Jesse Wilson47daf872011-11-23 11:42:45 -05001150 } else if (class_loader == NULL) {
1151 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1152 if (pair.second != NULL) {
1153 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1154 }
1155
1156 } else if (ClassLoader::UseCompileTimeClassPath()) {
1157 // first try the boot class path
1158 Class* system_class = FindSystemClass(descriptor);
1159 if (system_class != NULL) {
1160 return system_class;
1161 }
1162 CHECK(self->IsExceptionPending());
1163 self->ClearException();
1164
1165 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001166 const std::vector<const DexFile*>& class_path
1167 = ClassLoader::GetCompileTimeClassPath(class_loader);
1168 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001169 if (pair.second != NULL) {
1170 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001171 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001172
1173 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001174 std::string class_name_string(DescriptorToDot(descriptor));
Elliott Hughes09d4d012012-02-03 17:44:20 -08001175 ScopedThreadStateChange tsc(self, Thread::kNative);
Elliott Hughes748382f2012-01-26 18:07:38 -08001176 JNIEnv* env = self->GetJniEnv();
Jesse Wilson47daf872011-11-23 11:42:45 -05001177 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1178 CHECK(c.get() != NULL);
1179 // TODO: cache method?
1180 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1181 CHECK(mid != NULL);
1182 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1183 if (class_name_object.get() == NULL) {
1184 return NULL;
1185 }
1186 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
Ian Rogers761bfa82012-01-11 10:14:05 -08001187 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid,
1188 class_name_object.get()));
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001189 if (env->ExceptionCheck()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001190 // If the ClassLoader threw, pass that exception up.
1191 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001192 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001193 // broken loader - throw NPE to be compatible with Dalvik
1194 ThrowNullPointerException("ClassLoader.loadClass returned null for %s",
1195 class_name_string.c_str());
1196 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001197 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08001198 // success, return Class*
Ian Rogers6b0870d2011-12-15 19:38:12 -08001199 return Decode<Class*>(env, result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001200 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001201 }
1202
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001203 ThrowNoClassDefFoundError("Class %s not found", PrintableString(StringPiece(descriptor)).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001204 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001205}
1206
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001207Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001208 const ClassLoader* class_loader,
1209 const DexFile& dex_file,
1210 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001211 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001212 // Load the class from the dex file.
1213 if (!init_done_) {
1214 // finish up init of hand crafted class_roots_
1215 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001216 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001217 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001218 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001219 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001220 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001221 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001222 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001223 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001224 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001225 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001226 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001227 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001228 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001229 }
1230 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001231 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001232 }
1233 klass->SetDexCache(FindDexCache(dex_file));
1234 LoadClass(dex_file, dex_class_def, klass, class_loader);
1235 // Check for a pending exception during load
1236 Thread* self = Thread::Current();
1237 if (self->IsExceptionPending()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001238 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001239 return NULL;
1240 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001241 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001242 klass->SetClinitThreadId(self->GetTid());
1243 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001244 Class* existing = InsertClass(descriptor, klass.get(), false);
1245 if (existing != NULL) {
1246 // We failed to insert because we raced with another thread.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001247 klass->SetClinitThreadId(0);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001248 klass.reset(existing);
1249 return EnsureResolved(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001250 }
1251 // Finish loading (if necessary) by finding parents
1252 CHECK(!klass->IsLoaded());
1253 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1254 // Loading failed.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001255 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001256 lock.NotifyAll();
1257 return NULL;
1258 }
1259 CHECK(klass->IsLoaded());
1260 // Link the class (if necessary)
1261 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001262 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001263 // Linking failed.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001264 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001265 lock.NotifyAll();
1266 return NULL;
1267 }
1268 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001269
1270 /*
1271 * We send CLASS_PREPARE events to the debugger from here. The
1272 * definition of "preparation" is creating the static fields for a
1273 * class and initializing them to the standard default values, but not
1274 * executing any code (that comes later, during "initialization").
1275 *
1276 * We did the static preparation in LinkClass.
1277 *
1278 * The class has been prepared and resolved but possibly not yet verified
1279 * at this point.
1280 */
1281 Dbg::PostClassPrepare(klass.get());
1282
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001283 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001284}
1285
Brian Carlstrom4873d462011-08-21 15:23:39 -07001286// Precomputes size that will be needed for Class, matching LinkStaticFields
1287size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1288 const DexFile::ClassDef& dex_class_def) {
1289 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001290 size_t num_ref = 0;
1291 size_t num_32 = 0;
1292 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001293 if (class_data != NULL) {
1294 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1295 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001296 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001297 char c = descriptor[0];
1298 if (c == 'L' || c == '[') {
1299 num_ref++;
1300 } else if (c == 'J' || c == 'D') {
1301 num_64++;
1302 } else {
1303 num_32++;
1304 }
1305 }
1306 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001307 // start with generic class data
1308 size_t size = sizeof(Class);
1309 // follow with reference fields which must be contiguous at start
1310 size += (num_ref * sizeof(uint32_t));
1311 // if there are 64-bit fields to add, make sure they are aligned
1312 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1313 if (num_32 != 0) {
1314 // use an available 32-bit field for padding
1315 num_32--;
1316 }
1317 size += sizeof(uint32_t); // either way, we are adding a word
1318 DCHECK_EQ(size, RoundUp(size, 8));
1319 }
1320 // tack on any 64-bit fields now that alignment is assured
1321 size += (num_64 * sizeof(uint64_t));
1322 // tack on any remaining 32-bit fields
1323 size += (num_32 * sizeof(uint32_t));
1324 return size;
1325}
1326
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001327void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001328 // Every kind of method should at least get an invoke stub from the oat_method.
1329 // non-abstract methods also get their code pointers.
1330 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001331 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001332
1333 if (method->IsAbstract()) {
1334 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1335 return;
1336 }
1337 if (method->IsNative()) {
1338 // unregistering restores the dlsym lookup stub
1339 method->UnregisterNative();
jeffhao26c0a1a2012-01-17 16:28:33 -08001340 }
1341
1342 if (Runtime::Current()->IsMethodTracingActive()) {
1343#if defined(__arm__)
1344 Trace* tracer = Runtime::Current()->GetTracer();
1345 void* trace_stub = reinterpret_cast<void*>(art_trace_entry_from_code);
1346 tracer->SaveAndUpdateCode(method.get(), trace_stub);
1347#else
1348 UNIMPLEMENTED(WARNING);
1349#endif
Brian Carlstrom92827a52011-10-10 15:50:01 -07001350 }
1351}
1352
Brian Carlstromf615a612011-07-23 12:50:34 -07001353void ClassLinker::LoadClass(const DexFile& dex_file,
1354 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001355 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001356 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001357 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001358 CHECK(klass->GetDexCache() != NULL);
1359 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001360 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001361 CHECK(descriptor != NULL);
1362
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001363 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001364 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001365 // Make sure that none of our runtime-only flags are set.
1366 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001367 klass->SetAccessFlags(access_flags);
1368 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001369 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001370 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001371
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001372 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001373
Ian Rogers0571d352011-11-03 19:51:38 -07001374 // Load fields fields.
1375 const byte* class_data = dex_file.GetClassData(dex_class_def);
1376 if (class_data == NULL) {
1377 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001378 }
Ian Rogers0571d352011-11-03 19:51:38 -07001379 ClassDataItemIterator it(dex_file, class_data);
1380 if (it.NumStaticFields() != 0) {
1381 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1382 }
1383 if (it.NumInstanceFields() != 0) {
1384 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1385 }
1386 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1387 SirtRef<Field> sfield(AllocField());
1388 klass->SetStaticField(i, sfield.get());
1389 LoadField(dex_file, it, klass, sfield);
1390 }
1391 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1392 SirtRef<Field> ifield(AllocField());
1393 klass->SetInstanceField(i, ifield.get());
1394 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001395 }
1396
Brian Carlstromaded5f72011-10-07 17:15:04 -07001397 UniquePtr<const OatFile::OatClass> oat_class;
1398 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001399 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
1400 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << descriptor;
1401 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1402 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << descriptor;
1403 uint32_t class_def_index;
1404 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1405 CHECK(found) << dex_file.GetLocation() << " " << descriptor;
1406 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
1407 CHECK(oat_class.get() != NULL) << dex_file.GetLocation() << " " << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001408 }
Ian Rogers0571d352011-11-03 19:51:38 -07001409 // Load methods.
1410 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001411 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001412 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001413 }
Ian Rogers0571d352011-11-03 19:51:38 -07001414 if (it.NumVirtualMethods() != 0) {
1415 // TODO: append direct methods to class object
1416 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001417 }
Ian Rogers0571d352011-11-03 19:51:38 -07001418 size_t method_index = 0;
1419 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1420 SirtRef<Method> method(AllocMethod());
1421 klass->SetDirectMethod(i, method.get());
1422 LoadMethod(dex_file, it, klass, method);
1423 if (oat_class.get() != NULL) {
1424 LinkCode(method, oat_class.get(), method_index);
1425 }
1426 method_index++;
1427 }
1428 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1429 SirtRef<Method> method(AllocMethod());
1430 klass->SetVirtualMethod(i, method.get());
1431 LoadMethod(dex_file, it, klass, method);
1432 if (oat_class.get() != NULL) {
1433 LinkCode(method, oat_class.get(), method_index);
1434 }
1435 method_index++;
1436 }
1437 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001438}
1439
Ian Rogers0571d352011-11-03 19:51:38 -07001440void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1441 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001442 uint32_t field_idx = it.GetMemberIndex();
1443 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001444 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001445 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001446}
1447
Ian Rogers0571d352011-11-03 19:51:38 -07001448void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1449 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001450 uint32_t method_idx = it.GetMemberIndex();
1451 dst->SetDexMethodIndex(method_idx);
1452 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001453 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001454
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001455
1456 StringPiece method_name(dex_file.GetMethodName(method_id));
1457 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001458 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1459 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001460
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001461 if (method_name == "finalize") {
1462 // Create the prototype for a signature of "()V"
1463 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1464 if (void_string_id != NULL) {
1465 const DexFile::TypeId* void_type_id =
1466 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1467 if (void_type_id != NULL) {
1468 std::vector<uint16_t> no_args;
1469 const DexFile::ProtoId* finalizer_proto =
1470 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1471 if (finalizer_proto != NULL) {
1472 // We have the prototype in the dex file
1473 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1474 klass->SetFinalizable();
1475 } else {
1476 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1477 // The Enum class declares a "final" finalize() method to prevent subclasses from
1478 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1479 // subclasses, so we exclude it here.
1480 // We also want to avoid setting the flag on Object, where we know that finalize() is
1481 // empty.
1482 if (klass_descriptor != "Ljava/lang/Object;" &&
1483 klass_descriptor != "Ljava/lang/Enum;") {
1484 klass->SetFinalizable();
1485 }
1486 }
1487 }
1488 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001489 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001490 }
Ian Rogers0571d352011-11-03 19:51:38 -07001491 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001492 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001493
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001494 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1495 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001496 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1497 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001498}
1499
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001500void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001501 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1502 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001503}
1504
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001505void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1506 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001507 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001508 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001509}
1510
Brian Carlstromaded5f72011-10-07 17:15:04 -07001511bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001512 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001513 for (size_t i = 0; i != dex_files_.size(); ++i) {
1514 if (dex_files_[i] == &dex_file) {
1515 return true;
1516 }
1517 }
1518 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001519}
1520
Brian Carlstromaded5f72011-10-07 17:15:04 -07001521bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001522 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001523 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001524}
1525
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001526void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001527 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001528 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001529 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001530 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001531 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001532}
1533
Brian Carlstromaded5f72011-10-07 17:15:04 -07001534void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001535 {
1536 MutexLock mu(dex_lock_);
1537 if (IsDexFileRegisteredLocked(dex_file)) {
1538 return;
1539 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001540 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001541 // Don't alloc while holding the lock, since allocation may need to
1542 // suspend all threads and another thread may need the dex_lock_ to
1543 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001544 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001545 {
1546 MutexLock mu(dex_lock_);
1547 if (IsDexFileRegisteredLocked(dex_file)) {
1548 return;
1549 }
1550 RegisterDexFileLocked(dex_file, dex_cache);
1551 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001552}
1553
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001554void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001555 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001556 RegisterDexFileLocked(dex_file, dex_cache);
1557}
1558
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001559const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001560 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001561 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001562 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1563 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001564 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001565 }
1566 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001567 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001568 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001569}
1570
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001571DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001572 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001573 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001574 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001575 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001576 }
1577 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001578 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001579 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001580}
1581
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001582Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1583 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001584 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001585 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001586 CHECK(primitive_class != NULL);
1587 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001588 primitive_class->SetPrimitiveType(type);
1589 primitive_class->SetStatus(Class::kStatusInitialized);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001590 Class* existing = InsertClass(descriptor, primitive_class, false);
1591 CHECK(existing == NULL) << "InitPrimitiveClass(" << descriptor << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001592 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001593}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001594
Brian Carlstrombe977852011-07-19 14:54:54 -07001595// Create an array class (i.e. the class object for the array, not the
1596// array itself). "descriptor" looks like "[C" or "[[[[B" or
1597// "[Ljava/lang/String;".
1598//
1599// If "descriptor" refers to an array of primitives, look up the
1600// primitive type's internally-generated class object.
1601//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001602// "class_loader" is the class loader of the class that's referring to
1603// us. It's used to ensure that we're looking for the element type in
1604// the right context. It does NOT become the class loader for the
1605// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001606//
1607// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001608Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001609 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001610
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001611 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001612 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001613 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001614 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001615 return NULL;
1616 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001617
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001618 // See if the component type is already loaded. Array classes are
1619 // always associated with the class loader of their underlying
1620 // element type -- an array of Strings goes with the loader for
1621 // java/lang/String -- so we need to look for it there. (The
1622 // caller should have checked for the existence of the class
1623 // before calling here, but they did so with *their* class loader,
1624 // not the component type's loader.)
1625 //
1626 // If we find it, the caller adds "loader" to the class' initiating
1627 // loader list, which should prevent us from going through this again.
1628 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001629 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001630 // are the same, because our caller (FindClass) just did the
1631 // lookup. (Even if we get this wrong we still have correct behavior,
1632 // because we effectively do this lookup again when we add the new
1633 // class to the hash table --- necessary because of possible races with
1634 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001635 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001636 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001637 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001638 return new_class;
1639 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001640 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001641
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001642 // Fill out the fields in the Class.
1643 //
1644 // It is possible to execute some methods against arrays, because
1645 // all arrays are subclasses of java_lang_Object_, so we need to set
1646 // up a vtable. We can just point at the one in java_lang_Object_.
1647 //
1648 // Array classes are simple enough that we don't need to do a full
1649 // link step.
1650
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001651 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001652 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001653 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001654 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001655 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001656 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001657 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001658 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001659 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001660 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001661 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001662 }
1663 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001664 if (new_class.get() == NULL) {
1665 new_class.reset(AllocClass(sizeof(Class)));
1666 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001667 return NULL;
1668 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001669 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001670 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001671 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001672 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001673 new_class->SetSuperClass(java_lang_Object);
1674 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001675 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001676 new_class->SetClassLoader(component_type->GetClassLoader());
1677 new_class->SetStatus(Class::kStatusInitialized);
1678 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001679 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001680
1681
1682 // All arrays have java/lang/Cloneable and java/io/Serializable as
1683 // interfaces. We need to set that up here, so that stuff like
1684 // "instanceof" works right.
1685 //
1686 // Note: The GC could run during the call to FindSystemClass,
1687 // so we need to make sure the class object is GC-valid while we're in
1688 // there. Do this by clearing the interface list so the GC will just
1689 // think that the entries are null.
1690
1691
1692 // Use the single, global copies of "interfaces" and "iftable"
1693 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001694 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001695 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001696
1697 // Inherit access flags from the component type. Arrays can't be
1698 // used as a superclass or interface, so we want to add "final"
1699 // and remove "interface".
1700 //
1701 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001702 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001703 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001704 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1705 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001706
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001707 Class* existing = InsertClass(descriptor, new_class.get(), false);
1708 if (existing == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001709 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001710 }
1711 // Another thread must have loaded the class after we
1712 // started but before we finished. Abandon what we've
1713 // done.
1714 //
1715 // (Yes, this happens.)
1716
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001717 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001718}
1719
1720Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001721 switch (Primitive::GetType(type)) {
1722 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001723 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001724 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001725 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001726 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001727 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001728 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001729 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001730 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001731 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001732 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001733 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001734 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001735 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001736 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001737 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001738 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001739 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001740 case Primitive::kPrimNot:
1741 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001742 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001743 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001744 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001745 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001746}
1747
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001748Class* ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001749 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001750 DexCache* dex_cache = klass->GetDexCache();
1751 std::string source;
1752 if (dex_cache != NULL) {
1753 source += " from ";
1754 source += dex_cache->GetLocation()->ToModifiedUtf8();
1755 }
1756 LOG(INFO) << "Loaded class " << descriptor << source;
1757 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001758 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001759 MutexLock mu(classes_lock_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001760 Table& classes = image_class ? image_classes_ : classes_;
1761 Class* existing = LookupClass(descriptor.data(), klass->GetClassLoader(), hash, classes);
1762#ifndef NDEBUG
1763 // Check we don't have the class in the other table in error
1764 Table& other_classes = image_class ? classes_ : image_classes_;
1765 CHECK(LookupClass(descriptor.data(), klass->GetClassLoader(), hash, other_classes) == NULL);
1766#endif
1767 if (existing != NULL) {
1768 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07001769 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001770 classes.insert(std::make_pair(hash, klass));
1771 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001772}
1773
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001774bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1775 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001776 MutexLock mu(classes_lock_);
Elliott Hughese5448b52012-01-18 16:44:06 -08001777 typedef Table::iterator It; // TODO: C++0x auto
Brian Carlstromae826982011-11-09 01:33:42 -08001778 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001779 ClassHelper kh;
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001780 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001781 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001782 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001783 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001784 classes_.erase(it);
1785 return true;
1786 }
1787 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001788 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001789 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001790 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001791 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001792 image_classes_.erase(it);
1793 return true;
1794 }
1795 }
1796 return false;
1797}
1798
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001799Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1800 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001801 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001802 // TODO: determine if its better to search classes_ or image_classes_ first
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001803 Class* klass = LookupClass(descriptor, class_loader, hash, classes_);
1804 if (klass != NULL) {
1805 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001806 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001807 return LookupClass(descriptor, class_loader, hash, image_classes_);
1808}
1809
1810Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader,
1811 size_t hash, const Table& classes) {
1812 ClassHelper kh(NULL, this);
1813 typedef Table::const_iterator It; // TODO: C++0x auto
1814 for (It it = classes.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001815 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001816 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001817 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001818#ifndef NDEBUG
1819 for (++it; it != end && it->first == hash; ++it) {
Ian Rogersd85016c2012-02-03 18:27:34 -08001820 Class* klass2 = it->second;
1821 kh.ChangeClass(klass2);
1822 CHECK(!(strcmp(descriptor, kh.GetDescriptor()) == 0 && klass2->GetClassLoader() == class_loader))
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001823 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
Ian Rogersd85016c2012-02-03 18:27:34 -08001824 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001825 }
1826#endif
Ian Rogers5d76c432011-10-31 21:42:49 -07001827 return klass;
1828 }
1829 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001830 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001831}
1832
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001833void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001834 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001835 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001836 MutexLock mu(classes_lock_);
1837 typedef Table::const_iterator It; // TODO: C++0x auto
1838 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001839 ClassHelper kh(NULL, this);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001840 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001841 Class* klass = it->second;
1842 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001843 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001844 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001845 }
1846 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001847 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001848 Class* klass = it->second;
1849 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001850 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001851 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001852 }
1853 }
1854}
1855
Ian Rogersc20a83e2012-01-18 18:15:32 -08001856#ifndef NDEBUG
1857static void CheckMethodsHaveGcMaps(Class* klass) {
1858 if (!Runtime::Current()->IsStarted()) {
1859 return;
1860 }
1861 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
1862 Method* method = klass->GetDirectMethod(i);
1863 if (!method->IsNative() && !method->IsAbstract()) {
1864 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1865 }
1866 }
1867 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
1868 Method* method = klass->GetVirtualMethod(i);
1869 if (!method->IsNative() && !method->IsAbstract()) {
1870 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1871 }
1872 }
1873}
1874#else
1875static void CheckMethodsHaveGcMaps(Class* klass) {
1876}
1877#endif
1878
jeffhao98eacac2011-09-14 16:11:53 -07001879void ClassLinker::VerifyClass(Class* klass) {
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001880 ObjectLock lock(klass);
1881
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001882 // TODO: assert that the monitor on the Class is held
jeffhao98eacac2011-09-14 16:11:53 -07001883 if (klass->IsVerified()) {
1884 return;
1885 }
1886
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001887 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved) << PrettyClass(klass);
jeffhao98eacac2011-09-14 16:11:53 -07001888 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001889
Ian Rogers1c5eb702012-02-01 09:18:34 -08001890 // Verify super class
1891 Class* super = klass->GetSuperClass();
1892 std::string error_msg;
1893 if (super != NULL) {
1894 // Acquire lock to prevent races on verifying the super class
1895 ObjectLock lock(super);
1896
1897 if (!super->IsVerified() && !super->IsErroneous()) {
1898 Runtime::Current()->GetClassLinker()->VerifyClass(super);
1899 }
1900 if (!super->IsVerified()) {
1901 error_msg = "Rejecting class ";
1902 error_msg += PrettyDescriptor(klass);
1903 error_msg += " that attempts to sub-class erroneous class ";
1904 error_msg += PrettyDescriptor(super);
1905 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
1906 Thread* self = Thread::Current();
1907 SirtRef<Throwable> cause(self->GetException());
1908 if (cause.get() != NULL) {
1909 self->ClearException();
1910 }
1911 self->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
1912 if (cause.get() != NULL) {
1913 self->GetException()->SetCause(cause.get());
1914 }
1915 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyDescriptor(klass);
1916 klass->SetStatus(Class::kStatusError);
1917 return;
1918 }
1919 }
1920
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001921 // Try to use verification information from oat file, otherwise do runtime verification
1922 const DexFile& dex_file = FindDexFile(klass->GetDexCache());
Ian Rogers1c5eb702012-02-01 09:18:34 -08001923 if (VerifyClassUsingOatFile(dex_file, klass) ||
1924 verifier::DexVerifier::VerifyClass(klass, error_msg)) {
Ian Rogersc4762272012-02-01 15:55:55 -08001925 DCHECK(!Thread::Current()->IsExceptionPending());
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001926 // Make sure all classes referenced by catch blocks are resolved
1927 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001928 klass->SetStatus(Class::kStatusVerified);
Ian Rogersc20a83e2012-01-18 18:15:32 -08001929 // Sanity check that a verified class has GC maps on all methods
1930 CheckMethodsHaveGcMaps(klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001931 } else {
Ian Rogers09f6b562012-01-31 21:58:52 -08001932 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass)
Ian Rogers1c5eb702012-02-01 09:18:34 -08001933 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
1934 << " because: " << error_msg;
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001935 Thread* self = Thread::Current();
Ian Rogersc4762272012-02-01 15:55:55 -08001936 CHECK(!self->IsExceptionPending());
Ian Rogers1c5eb702012-02-01 09:18:34 -08001937 self->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
1938 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyDescriptor(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001939 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001940 }
jeffhao98eacac2011-09-14 16:11:53 -07001941}
1942
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001943bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, Class* klass) {
1944 if (!Runtime::Current()->IsStarted()) {
1945 return false;
1946 }
1947 if (ClassLoader::UseCompileTimeClassPath()) {
1948 return false;
1949 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001950 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
1951 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001952 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001953 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001954 const char* descriptor = ClassHelper(klass).GetDescriptor();
1955 uint32_t class_def_index;
1956 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001957 CHECK(found) << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001958 UniquePtr<const OatFile::OatClass> oat_class(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001959 CHECK(oat_class.get() != NULL)
1960 << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001961 Class::Status status = oat_class->GetStatus();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001962 if (status == Class::kStatusVerified || status == Class::kStatusInitialized) {
1963 return true;
1964 }
Ian Rogersc4762272012-02-01 15:55:55 -08001965 if (status == Class::kStatusError) {
1966 // Compile time verification failed. Compile time verification can fail because we have
1967 // incomplete type information. Consider the following:
1968 // class ... {
1969 // Foo x;
1970 // .... () {
1971 // if (...) {
1972 // v1 gets assigned a type of resolved class Foo
1973 // } else {
1974 // v1 gets assigned a type of unresolved class Bar
1975 // }
1976 // iput x = v1
1977 // } }
1978 // when we merge v1 following the if-the-else it results in Conflict
1979 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
1980 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
1981 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
1982 // at compile time).
1983 return false;
1984 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001985 if (status == Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08001986 // Status is uninitialized if we couldn't determine the status at compile time, for example,
1987 // not loading the class.
1988 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
1989 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001990 return false;
1991 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001992 LOG(FATAL) << "Unexpected class status: " << status
1993 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
1994
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001995 return false;
1996}
1997
1998void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, Class* klass) {
1999 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
2000 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
2001 }
2002 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
2003 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
2004 }
2005}
2006
2007void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, Method* method) {
2008 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
2009 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
2010 if (code_item == NULL) {
2011 return; // native or abstract method
2012 }
2013 if (code_item->tries_size_ == 0) {
2014 return; // nothing to process
2015 }
2016 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
2017 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2018 ClassLinker* linker = Runtime::Current()->GetClassLinker();
2019 for (uint32_t idx = 0; idx < handlers_size; idx++) {
2020 CatchHandlerIterator iterator(handlers_ptr);
2021 for (; iterator.HasNext(); iterator.Next()) {
2022 // Ensure exception types are resolved so that they don't need resolution to be delivered,
2023 // unresolved exception types will be ignored by exception delivery
2024 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
2025 Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
2026 if (exception_type == NULL) {
2027 DCHECK(Thread::Current()->IsExceptionPending());
2028 Thread::Current()->ClearException();
2029 }
2030 }
2031 }
2032 handlers_ptr = iterator.EndDataPointer();
2033 }
2034}
2035
Ian Rogersc2b44472011-12-14 21:17:17 -08002036static void CheckProxyConstructor(Method* constructor);
2037static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
2038
Jesse Wilson95caa792011-10-12 18:14:17 -04002039Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002040 ClassLoader* loader, ObjectArray<Method>* methods,
2041 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08002042 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002043 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08002044 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04002045 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002046 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002047 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002048 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002049 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07002050 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002051 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08002052
2053 klass->SetStatus(Class::kStatusIdx);
2054
2055 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
2056
2057 // Create static field that holds throws, instance fields are inherited
2058 klass->SetSFields(AllocObjectArray<Field>(1));
2059 SirtRef<Field> sfield(AllocField());
2060 klass->SetStaticField(0, sfield.get());
2061 sfield->SetDexFieldIndex(-1);
2062 sfield->SetDeclaringClass(klass.get());
2063 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002064
Ian Rogers466bb252011-10-14 03:29:56 -07002065 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04002066 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002067 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04002068
Ian Rogers466bb252011-10-14 03:29:56 -07002069 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04002070 size_t num_virtual_methods = methods->GetLength();
2071 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
2072 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002073 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002074 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04002075 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002076
2077 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
2078 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
2079 DCHECK(!Thread::Current()->IsExceptionPending());
2080
2081 // Link the fields and virtual methods, creating vtable and iftables
2082 if (!LinkClass(klass, interfaces)) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002083 klass->SetStatus(Class::kStatusError);
Jesse Wilson95caa792011-10-12 18:14:17 -04002084 return NULL;
2085 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002086 sfield->SetObject(NULL, throws); // initialize throws field
2087 klass->SetStatus(Class::kStatusInitialized);
2088
2089 // sanity checks
2090#ifndef NDEBUG
2091 bool debug = true;
2092#else
2093 bool debug = false;
2094#endif
2095 if (debug) {
2096 CHECK(klass->GetIFields() == NULL);
2097 CheckProxyConstructor(klass->GetDirectMethod(0));
2098 for (size_t i = 0; i < num_virtual_methods; ++i) {
2099 SirtRef<Method> prototype(methods->Get(i));
2100 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
2101 }
Brian Carlstrom89521892011-12-07 22:05:07 -08002102 std::string throws_field_name("java.lang.Class[][] ");
Ian Rogersc2b44472011-12-14 21:17:17 -08002103 throws_field_name += name->ToModifiedUtf8();
2104 throws_field_name += ".throws";
2105 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
2106
2107 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
2108 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
2109 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002110 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04002111}
2112
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002113std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
2114 DCHECK(proxy_class->IsProxyClass());
2115 String* name = proxy_class->GetName();
2116 DCHECK(name != NULL);
2117 return DotToDescriptor(name->ToModifiedUtf8().c_str());
2118}
2119
Ian Rogers16f93672012-02-14 12:29:06 -08002120Method* ClassLinker::FindMethodForProxy(const Class* proxy_class, const Method* proxy_method) {
2121 DCHECK(proxy_class->IsProxyClass());
2122 DCHECK(proxy_method->IsProxyMethod());
2123 // Locate the dex cache of the original interface/Object
2124 DexCache* dex_cache = NULL;
2125 {
2126 ObjectArray<Class>* resolved_types = proxy_method->GetDexCacheResolvedTypes();
2127 MutexLock mu(dex_lock_);
2128 for (size_t i = 0; i != dex_caches_.size(); ++i) {
2129 if (dex_caches_[i]->GetResolvedTypes() == resolved_types) {
2130 dex_cache = dex_caches_[i];
2131 break;
2132 }
2133 }
2134 }
2135 CHECK(dex_cache != NULL);
2136 uint32_t method_idx = proxy_method->GetDexMethodIndex();
2137 Method* resolved_method = dex_cache->GetResolvedMethod(method_idx);
2138 CHECK(resolved_method != NULL);
2139 return resolved_method;
2140}
2141
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002142
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
Ian Rogers16f93672012-02-14 12:29:06 -08002168 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
2169 prototype.get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002170 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07002171 // as necessary
2172 Method* method = down_cast<Method*>(prototype->Clone());
2173
2174 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
2175 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002176 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07002177 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002178
Ian Rogers466bb252011-10-14 03:29:56 -07002179 // At runtime the method looks like a reference and argument saving method, clone the code
2180 // related parameters from this method.
2181 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
2182 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
2183 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
2184 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
2185 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogers16f93672012-02-14 12:29:06 -08002186
Ian Rogersc2b44472011-12-14 21:17:17 -08002187 return method;
2188}
Jesse Wilson95caa792011-10-12 18:14:17 -04002189
Ian Rogersc2b44472011-12-14 21:17:17 -08002190static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07002191 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002192 CHECK(!prototype->IsFinal());
2193 CHECK(method->IsFinal());
2194 CHECK(!method->IsAbstract());
2195 MethodHelper mh(method);
2196 const char* method_name = mh.GetName();
2197 const char* method_shorty = mh.GetShorty();
2198 Class* method_return = mh.GetReturnType();
2199
2200 mh.ChangeMethod(prototype.get());
2201
2202 CHECK_STREQ(mh.GetName(), method_name);
2203 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07002204
2205 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002206 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04002207}
2208
Brian Carlstrom25c33252011-09-18 15:58:35 -07002209bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002210 CHECK(klass->IsResolved() || klass->IsErroneous())
2211 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002212
Carl Shapirob5573532011-07-12 18:22:59 -07002213 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002214
Brian Carlstrom25c33252011-09-18 15:58:35 -07002215 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002216 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002217 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002218 ObjectLock lock(klass);
2219
Brian Carlstromd1422f82011-09-28 11:37:09 -07002220 if (klass->GetStatus() == Class::kStatusInitialized) {
2221 return true;
2222 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002223
Brian Carlstromd1422f82011-09-28 11:37:09 -07002224 if (klass->IsErroneous()) {
2225 ThrowEarlierClassFailure(klass);
2226 return false;
2227 }
2228
2229 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07002230 VerifyClass(klass);
2231 if (klass->GetStatus() != Class::kStatusVerified) {
Ian Rogers595799e2012-01-11 17:32:51 -08002232 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002233 return false;
2234 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002235 }
2236
Brian Carlstrom25c33252011-09-18 15:58:35 -07002237 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
2238 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002239 // if the class has a <clinit> but we can't run it during compilation,
Ian Rogers1bddec32012-02-04 12:27:34 -08002240 // don't bother going to kStatusInitializing. We return false so that
2241 // sub-classes don't believe this class is initialized.
2242 return false;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002243 }
2244
Brian Carlstromd1422f82011-09-28 11:37:09 -07002245 // If the class is kStatusInitializing, either this thread is
2246 // initializing higher up the stack or another thread has beat us
2247 // to initializing and we need to wait. Either way, this
2248 // invocation of InitializeClass will not be responsible for
2249 // running <clinit> and will return.
2250 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002251 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002252 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002253 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002254 return true;
2255 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002256 // No. That's fine. Wait for another thread to finish initializing.
2257 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002258 }
2259
2260 if (!ValidateSuperClassDescriptors(klass)) {
2261 klass->SetStatus(Class::kStatusError);
2262 return false;
2263 }
2264
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002265 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified) << PrettyClass(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002266
Elliott Hughesdcc24742011-09-07 14:02:44 -07002267 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002268 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002269 }
2270
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002271 uint64_t t0 = NanoTime();
2272
Brian Carlstrom25c33252011-09-18 15:58:35 -07002273 if (!InitializeSuperClass(klass, can_run_clinit)) {
Ian Rogers1bddec32012-02-04 12:27:34 -08002274 // Super class initialization failed, this can be because we can't run
2275 // super-class class initializers in which case we'll be verified.
2276 // Otherwise this class is erroneous.
2277 if (!can_run_clinit) {
2278 CHECK(klass->IsVerified());
2279 } else {
2280 CHECK(klass->IsErroneous());
2281 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002282 return false;
2283 }
2284
2285 InitializeStaticFields(klass);
2286
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002287 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002288 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002289 }
2290
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002291 uint64_t t1 = NanoTime();
2292
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002293 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002294 {
2295 ObjectLock lock(klass);
2296
2297 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002298 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002299 klass->SetStatus(Class::kStatusError);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002300 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002301 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002302 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2303 RuntimeStats* thread_stats = self->GetStats();
2304 ++global_stats->class_init_count;
2305 ++thread_stats->class_init_count;
2306 global_stats->class_init_time_ns += (t1 - t0);
2307 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002308 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002309 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002310 ClassHelper kh(klass);
2311 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002312 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002313 }
2314 lock.NotifyAll();
2315 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002316 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002317}
2318
Brian Carlstromd1422f82011-09-28 11:37:09 -07002319bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
2320 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002321 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002322 lock.Wait();
2323
2324 // When we wake up, repeat the test for init-in-progress. If
2325 // there's an exception pending (only possible if
2326 // "interruptShouldThrow" was set), bail out.
2327 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002328 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002329 klass->SetStatus(Class::kStatusError);
2330 return false;
2331 }
2332 // Spurious wakeup? Go back to waiting.
2333 if (klass->GetStatus() == Class::kStatusInitializing) {
2334 continue;
2335 }
2336 if (klass->IsErroneous()) {
2337 // The caller wants an exception, but it was thrown in a
2338 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002339 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002340 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002341 return false;
2342 }
2343 if (klass->IsInitialized()) {
2344 return true;
2345 }
2346 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2347 }
2348 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2349}
2350
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002351bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2352 if (klass->IsInterface()) {
2353 return true;
2354 }
2355 // begin with the methods local to the superclass
2356 if (klass->HasSuperClass() &&
2357 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2358 const Class* super = klass->GetSuperClass();
Ian Rogers595799e2012-01-11 17:32:51 -08002359 for (int i = super->GetVTable()->GetLength() - 1; i >= 0; --i) {
2360 const Method* method = klass->GetVTable()->Get(i);
2361 if (method != super->GetVTable()->Get(i) &&
2362 !IsSameMethodSignatureInDifferentClassContexts(method, super, klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002363 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2364 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2365 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002366 return false;
2367 }
2368 }
2369 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002370 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2371 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2372 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002373 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2374 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002375 const Method* method = interface_entry->GetMethodArray()->Get(j);
Ian Rogers595799e2012-01-11 17:32:51 -08002376 if (!IsSameMethodSignatureInDifferentClassContexts(method, interface,
2377 method->GetDeclaringClass())) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002378 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2379 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2380 PrettyMethod(method).c_str(),
2381 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002382 return false;
2383 }
2384 }
2385 }
2386 }
2387 return true;
2388}
2389
Ian Rogers595799e2012-01-11 17:32:51 -08002390// Returns true if classes referenced by the signature of the method are the
2391// same classes in klass1 as they are in klass2.
2392bool ClassLinker::IsSameMethodSignatureInDifferentClassContexts(const Method* method,
2393 const Class* klass1,
2394 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002395 if (klass1 == klass2) {
2396 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002397 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002398 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002399 const DexFile::ProtoId& proto_id =
2400 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002401 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2402 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002403 if (descriptor == NULL) {
2404 break;
2405 }
2406 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2407 // Found a non-primitive type.
Ian Rogers595799e2012-01-11 17:32:51 -08002408 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002409 return false;
2410 }
2411 }
2412 }
2413 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002414 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002415 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Ian Rogers595799e2012-01-11 17:32:51 -08002416 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002417 return false;
2418 }
2419 }
2420 return true;
2421}
2422
Ian Rogers595799e2012-01-11 17:32:51 -08002423// Returns true if the descriptor resolves to the same class in the context of klass1 and klass2.
2424bool ClassLinker::IsSameDescriptorInDifferentClassContexts(const char* descriptor,
2425 const Class* klass1,
2426 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002427 CHECK(descriptor != NULL);
2428 CHECK(klass1 != NULL);
2429 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002430 if (klass1 == klass2) {
2431 return true;
2432 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002433 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Ian Rogers595799e2012-01-11 17:32:51 -08002434 if (found1 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002435 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002436 }
Ian Rogers595799e2012-01-11 17:32:51 -08002437 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
2438 if (found2 == NULL) {
2439 Thread::Current()->ClearException();
2440 }
2441 return found1 == found2;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002442}
2443
Brian Carlstrom25c33252011-09-18 15:58:35 -07002444bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002445 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002446 if (!klass->IsInterface() && klass->HasSuperClass()) {
2447 Class* super_class = klass->GetSuperClass();
2448 if (super_class->GetStatus() != Class::kStatusInitialized) {
2449 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002450 Thread* self = Thread::Current();
2451 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002452 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002453 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002454 // TODO: check for a pending exception
2455 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002456 if (!can_run_clinit) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002457 // Don't set status to error when we can't run <clinit>.
2458 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing) << PrettyClass(klass);
2459 klass->SetStatus(Class::kStatusVerified);
2460 return false;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002461 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002462 klass->SetStatus(Class::kStatusError);
2463 klass->NotifyAll();
2464 return false;
2465 }
2466 }
2467 }
2468 return true;
2469}
2470
Brian Carlstrom25c33252011-09-18 15:58:35 -07002471bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002472 CHECK(c != NULL);
2473 if (c->IsInitialized()) {
2474 return true;
2475 }
2476
Elliott Hughes5f791332011-09-15 17:45:30 -07002477 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002478 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Ian Rogers595799e2012-01-11 17:32:51 -08002479 bool success = InitializeClass(c, can_run_clinit);
2480 if (!success) {
Ian Rogers1bddec32012-02-04 12:27:34 -08002481 CHECK(self->IsExceptionPending() || !can_run_clinit) << PrettyClass(c);
Ian Rogers595799e2012-01-11 17:32:51 -08002482 }
2483 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002484}
2485
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002486void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002487 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002488 const ClassLoader* cl = c->GetClassLoader();
2489 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002490 ClassDataItemIterator it(dex_file, class_data);
2491 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2492 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002493 }
2494}
2495
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002496void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002497 size_t num_static_fields = klass->NumStaticFields();
2498 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002499 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002500 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002501 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002502 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002503 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002504 return;
2505 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002506 ClassHelper kh(klass);
2507 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002508 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002509 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002510 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002511
Ian Rogers0571d352011-11-03 19:51:38 -07002512 if (it.HasNext()) {
2513 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2514 std::map<uint32_t, Field*> field_map;
2515 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2516 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2517 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002518 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002519 }
2520}
2521
Ian Rogersc2b44472011-12-14 21:17:17 -08002522bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002523 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002524 if (!LinkSuperClass(klass)) {
2525 return false;
2526 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002527 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002528 return false;
2529 }
2530 if (!LinkInstanceFields(klass)) {
2531 return false;
2532 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002533 if (!LinkStaticFields(klass)) {
2534 return false;
2535 }
2536 CreateReferenceInstanceOffsets(klass);
2537 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002538 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2539 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002540 return true;
2541}
2542
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002543bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002544 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002545 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2546 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
Ian Rogerscab01012012-01-10 17:35:46 -08002547 CHECK(class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002548 uint16_t super_class_idx = class_def->superclass_idx_;
2549 if (super_class_idx != DexFile::kDexNoIndex16) {
2550 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002551 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002552 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002553 return false;
2554 }
Ian Rogersbe125a92012-01-11 15:19:49 -08002555 // Verify
2556 if (!klass->CanAccess(super_class)) {
2557 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2558 "Class %s extended by class %s is inaccessible",
2559 PrettyDescriptor(super_class).c_str(),
2560 PrettyDescriptor(klass.get()).c_str());
2561 return false;
2562 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002563 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002564 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002565 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2566 if (interfaces != NULL) {
2567 for (size_t i = 0; i < interfaces->Size(); i++) {
2568 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2569 Class* interface = ResolveType(dex_file, idx, klass.get());
2570 if (interface == NULL) {
2571 DCHECK(Thread::Current()->IsExceptionPending());
2572 return false;
2573 }
2574 // Verify
2575 if (!klass->CanAccess(interface)) {
2576 // TODO: the RI seemed to ignore this in my testing.
2577 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2578 "Interface %s implemented by class %s is inaccessible",
2579 PrettyDescriptor(interface).c_str(),
2580 PrettyDescriptor(klass.get()).c_str());
2581 return false;
2582 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002583 }
2584 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002585 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002586 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002587 return true;
2588}
2589
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002590bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002591 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002592 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002593 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002594 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002595 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002596 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002597 return false;
2598 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002599 return true;
2600 }
2601 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002602 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002603 return false;
2604 }
2605 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002606 if (super->IsFinal() || super->IsInterface()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002607 Thread* self = Thread::Current();
2608 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002609 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002610 PrettyDescriptor(super).c_str(),
2611 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002612 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002613 return false;
2614 }
2615 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002616 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002617 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002618 PrettyDescriptor(super).c_str(),
2619 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002620 return false;
2621 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002622
2623 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2624 if (super->IsFinalizable()) {
2625 klass->SetFinalizable();
2626 }
2627
Elliott Hughes2da50362011-10-10 16:57:08 -07002628 // Inherit reference flags (if any) from the superclass.
2629 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2630 if (reference_flags != 0) {
2631 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2632 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002633 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002634 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002635 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002636 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002637 return false;
2638 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002639
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002640#ifndef NDEBUG
2641 // Ensure super classes are fully resolved prior to resolving fields..
2642 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002643 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002644 super = super->GetSuperClass();
2645 }
2646#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002647 return true;
2648}
2649
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002650// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002651bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002652 if (klass->IsInterface()) {
2653 // No vtable.
2654 size_t count = klass->NumVirtualMethods();
2655 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002656 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002657 return false;
2658 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002659 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002660 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002661 }
jeffhaobdb76512011-09-07 11:43:16 -07002662 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002663 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002664 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002665 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002666 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002667 }
2668 return true;
2669}
2670
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002671bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002672 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002673 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2674 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002675 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002676 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002677 SirtRef<ObjectArray<Method> > vtable(klass->GetSuperClass()->GetVTable()->CopyOf(max_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002678 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002679 MethodHelper local_mh(NULL, this);
2680 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002681 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002682 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002683 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002684 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002685 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002686 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002687 super_mh.ChangeMethod(super_method);
2688 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002689 // Verify
2690 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002691 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002692 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002693 PrettyDescriptor(klass.get()).c_str(),
2694 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002695 return false;
2696 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002697 vtable->Set(j, local_method);
2698 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002699 break;
2700 }
2701 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002702 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002703 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002704 vtable->Set(actual_count, local_method);
2705 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002706 actual_count += 1;
2707 }
2708 }
2709 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002710 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002711 return false;
2712 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002713 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002714 CHECK_LE(actual_count, max_count);
2715 if (actual_count < max_count) {
Ian Rogers30fab402012-01-23 15:43:46 -08002716 vtable.reset(vtable->CopyOf(actual_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002717 }
Ian Rogers30fab402012-01-23 15:43:46 -08002718 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002719 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002720 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002721 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002722 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002723 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002724 return false;
2725 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002726 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002727 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002728 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2729 vtable->Set(i, virtual_method);
2730 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002731 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002732 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002733 }
2734 return true;
2735}
2736
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002737bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002738 size_t super_ifcount;
2739 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002740 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002741 } else {
2742 super_ifcount = 0;
2743 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002744 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002745 ClassHelper kh(klass.get(), this);
2746 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2747 ifcount += num_interfaces;
2748 for (size_t i = 0; i < num_interfaces; i++) {
2749 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2750 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002751 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002752 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002753 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002754 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002755 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002756 return true;
2757 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002758 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002759 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002760 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2761 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogersb52b01a2012-01-12 17:01:38 -08002762 Class* super_interface = super_iftable->Get(i)->GetInterface();
2763 iftable->Set(i, AllocInterfaceEntry(super_interface));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002764 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002765 }
2766 // Flatten the interface inheritance hierarchy.
2767 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002768 for (size_t i = 0; i < num_interfaces; i++) {
2769 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002770 DCHECK(interface != NULL);
2771 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002772 ClassHelper ih(interface);
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002773 Thread* self = Thread::Current();
2774 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002775 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002776 PrettyDescriptor(klass.get()).c_str(),
2777 PrettyDescriptor(ih.GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002778 return false;
2779 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002780 // Check if interface is already in iftable
2781 bool duplicate = false;
2782 for (size_t j = 0; j < idx; j++) {
2783 Class* existing_interface = iftable->Get(j)->GetInterface();
2784 if (existing_interface == interface) {
2785 duplicate = true;
2786 break;
2787 }
2788 }
2789 if (!duplicate) {
2790 // Add this non-duplicate interface.
2791 iftable->Set(idx++, AllocInterfaceEntry(interface));
2792 // Add this interface's non-duplicate super-interfaces.
2793 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2794 Class* super_interface = interface->GetIfTable()->Get(j)->GetInterface();
2795 bool super_duplicate = false;
2796 for (size_t k = 0; k < idx; k++) {
2797 Class* existing_interface = iftable->Get(k)->GetInterface();
2798 if (existing_interface == super_interface) {
2799 super_duplicate = true;
2800 break;
2801 }
2802 }
2803 if (!super_duplicate) {
2804 iftable->Set(idx++, AllocInterfaceEntry(super_interface));
2805 }
2806 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002807 }
2808 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002809 // Shrink iftable in case duplicates were found
2810 if (idx < ifcount) {
2811 iftable.reset(iftable->CopyOf(idx));
2812 ifcount = idx;
2813 } else {
2814 CHECK_EQ(idx, ifcount);
2815 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002816 klass->SetIfTable(iftable.get());
Elliott Hughes4681c802011-09-25 18:04:37 -07002817
2818 // If we're an interface, we don't need the vtable pointers, so we're done.
2819 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002820 return true;
2821 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002822 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002823 MethodHelper vtable_mh(NULL, this);
2824 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002825 for (size_t i = 0; i < ifcount; ++i) {
2826 InterfaceEntry* interface_entry = iftable->Get(i);
2827 Class* interface = interface_entry->GetInterface();
2828 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2829 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002830 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002831 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2832 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002833 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002834 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002835 // For each method listed in the interface's method list, find the
2836 // matching method in our class's method list. We want to favor the
2837 // subclass over the superclass, which just requires walking
2838 // back from the end of the vtable. (This only matters if the
2839 // superclass defines a private method and this class redefines
2840 // it -- otherwise it would use the same vtable slot. In .dex files
2841 // those don't end up in the virtual method table, so it shouldn't
2842 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002843 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2844 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002845 vtable_mh.ChangeMethod(vtable_method);
2846 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002847 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002848 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002849 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002850 return false;
2851 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002852 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002853 break;
2854 }
2855 }
2856 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002857 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002858 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002859 Method* mir_method = miranda_list[mir];
2860 vtable_mh.ChangeMethod(mir_method);
2861 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002862 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002863 break;
2864 }
2865 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002866 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002867 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002868 miranda_method.reset(AllocMethod());
2869 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2870 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002871 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002872 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002873 }
2874 }
2875 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002876 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002877 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002878 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002879 klass->SetVirtualMethods((old_method_count == 0)
2880 ? AllocObjectArray<Method>(new_method_count)
2881 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002882
Ian Rogers30fab402012-01-23 15:43:46 -08002883 SirtRef<ObjectArray<Method> > vtable(klass->GetVTableDuringLinking());
2884 CHECK(vtable.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002885 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002886 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers30fab402012-01-23 15:43:46 -08002887 vtable.reset(vtable->CopyOf(new_vtable_count));
Elliott Hughes4681c802011-09-25 18:04:37 -07002888 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002889 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002890 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002891 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2892 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2893 klass->SetVirtualMethod(old_method_count + i, method);
2894 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002895 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002896 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002897 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002898 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002899
2900 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2901 for (int i = 0; i < vtable->GetLength(); ++i) {
2902 CHECK(vtable->Get(i) != NULL);
2903 }
2904
2905// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2906
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002907 return true;
2908}
2909
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002910bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2911 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002912 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002913}
2914
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002915bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2916 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002917 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002918 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002919 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002920 return success;
2921}
2922
Brian Carlstromdbc05252011-09-09 01:59:59 -07002923struct LinkFieldsComparator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002924 explicit LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002925 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002926 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002927 fh_->ChangeField(field1);
2928 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2929 fh_->ChangeField(field2);
2930 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002931 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2932 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2933 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2934 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002935 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2936 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2937 if (order1 != order2) {
2938 return order1 < order2;
2939 }
2940
2941 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002942 fh_->ChangeField(field1);
2943 StringPiece name1(fh_->GetName());
2944 fh_->ChangeField(field2);
2945 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002946 return name1 < name2;
2947 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002948
2949 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002950};
2951
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002952bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002953 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002954 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002955
2956 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002957 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002958
2959 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002960 size_t size;
2961 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002962 if (is_static) {
2963 size = klass->GetClassSize();
2964 field_offset = Class::FieldsOffset();
2965 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002966 Class* super_class = klass->GetSuperClass();
2967 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002968 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002969 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002970 }
2971 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002972 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002973
Brian Carlstromdbc05252011-09-09 01:59:59 -07002974 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002975
Brian Carlstromdbc05252011-09-09 01:59:59 -07002976 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002977 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002978 std::deque<Field*> grouped_and_sorted_fields;
2979 for (size_t i = 0; i < num_fields; i++) {
2980 grouped_and_sorted_fields.push_back(fields->Get(i));
2981 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002982 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002983 std::sort(grouped_and_sorted_fields.begin(),
2984 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002985 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002986
2987 // References should be at the front.
2988 size_t current_field = 0;
2989 size_t num_reference_fields = 0;
2990 for (; current_field < num_fields; current_field++) {
2991 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002992 fh.ChangeField(field);
2993 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002994 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002995 if (isPrimitive) {
2996 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002997 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002998 grouped_and_sorted_fields.pop_front();
2999 num_reference_fields++;
3000 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003001 field->SetOffset(field_offset);
3002 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003003 }
3004
3005 // Now we want to pack all of the double-wide fields together. If
3006 // we're not aligned, though, we want to shuffle one 32-bit field
3007 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07003008 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003009 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
3010 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003011 fh.ChangeField(field);
3012 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003013 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
3014 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003015 continue;
3016 }
3017 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003018 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003019 // drop the consumed field
3020 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
3021 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003022 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07003023 // whether we found a 32-bit field for padding or not, we advance
3024 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003025 }
3026
3027 // Alignment is good, shuffle any double-wide fields forward, and
3028 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07003029 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07003030 while (!grouped_and_sorted_fields.empty()) {
3031 Field* field = grouped_and_sorted_fields.front();
3032 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003033 fh.ChangeField(field);
3034 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003035 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07003036 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003037 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003038 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003039 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07003040 ? sizeof(uint64_t)
3041 : sizeof(uint32_t)));
3042 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003043 }
3044
Elliott Hughesadb460d2011-10-05 17:02:34 -07003045 // 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 -08003046 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
3047 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07003048 // We know there are no non-reference fields in the Reference classes, and we know
3049 // that 'referent' is alphabetically last, so this is easy...
3050 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003051 fh.ChangeField(fields->Get(num_fields - 1));
Elliott Hughesba8eee12012-01-24 20:25:24 -08003052 CHECK_STREQ(fh.GetName(), "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07003053 --num_reference_fields;
3054 }
3055
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003056#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07003057 // Make sure that all reference fields appear before
3058 // non-reference fields, and all double-wide fields are aligned.
3059 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07003060 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003061 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003062 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003063 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003064 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07003065 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07003066 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
3067 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003068 fh.ChangeField(field);
3069 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003070 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003071 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07003072 is_primitive = true; // We lied above, so we have to expect a lie here.
3073 }
3074 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07003075 if (!seen_non_ref) {
3076 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003077 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003078 }
Brian Carlstrombe977852011-07-19 14:54:54 -07003079 } else {
3080 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003081 }
3082 }
Brian Carlstrombe977852011-07-19 14:54:54 -07003083 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003084 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003085 }
3086#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003087 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003088 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003089 if (is_static) {
3090 klass->SetNumReferenceStaticFields(num_reference_fields);
3091 klass->SetClassSize(size);
3092 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003093 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003094 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003095 klass->SetObjectSize(size);
3096 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003097 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003098 return true;
3099}
3100
3101// Set the bitmap of reference offsets, refOffsets, from the ifields
3102// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003103void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003104 uint32_t reference_offsets = 0;
3105 Class* super_class = klass->GetSuperClass();
3106 if (super_class != NULL) {
3107 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003108 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003109 if (reference_offsets == CLASS_WALK_SUPER) {
3110 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003111 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003112 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003113 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003114 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003115}
3116
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003117void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003118 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003119}
3120
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003121void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003122 uint32_t reference_offsets) {
3123 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003124 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
3125 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003126 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003127 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003128 // All of the fields that contain object references are guaranteed
3129 // to be at the beginning of the fields list.
3130 for (size_t i = 0; i < num_reference_fields; ++i) {
3131 // Note that byte_offset is the offset from the beginning of
3132 // object, not the offset into instance data
3133 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003134 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003135 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
3136 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
3137 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07003138 CHECK_NE(new_bit, 0U);
3139 reference_offsets |= new_bit;
3140 } else {
3141 reference_offsets = CLASS_WALK_SUPER;
3142 break;
3143 }
3144 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003145 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003146 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003147 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003148 } else {
3149 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003150 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003151}
3152
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003153String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07003154 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003155 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003156 if (resolved != NULL) {
3157 return resolved;
3158 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003159 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
3160 int32_t utf16_length = dex_file.GetStringLength(string_id);
3161 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07003162 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003163 dex_cache->SetResolvedString(string_idx, string);
3164 return string;
3165}
3166
3167Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003168 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003169 DexCache* dex_cache,
3170 const ClassLoader* class_loader) {
3171 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003172 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07003173 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003174 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003175 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05003176 // TODO: we used to throw here if resolved's class loader was not the
3177 // boot class loader. This was to permit different classes with the
3178 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003179 dex_cache->SetResolvedType(type_idx, resolved);
3180 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08003181 CHECK(Thread::Current()->IsExceptionPending())
3182 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003183 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003184 }
3185 return resolved;
3186}
3187
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003188Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
3189 uint32_t method_idx,
3190 DexCache* dex_cache,
3191 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003192 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003193 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
3194 if (resolved != NULL) {
3195 return resolved;
3196 }
3197 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3198 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
3199 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07003200 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003201 return NULL;
3202 }
3203
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003204 if (is_direct) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003205 resolved = klass->FindDirectMethod(dex_cache, method_idx);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003206 } else if (klass->IsInterface()) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003207 resolved = klass->FindInterfaceMethod(dex_cache, method_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003208 } else {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003209 resolved = klass->FindVirtualMethod(dex_cache, method_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003210 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003211
3212 if (resolved == NULL) {
3213 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
3214 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
3215 if (is_direct) {
3216 resolved = klass->FindDirectMethod(name, signature);
3217 } else if (klass->IsInterface()) {
3218 resolved = klass->FindInterfaceMethod(name, signature);
3219 } else {
3220 resolved = klass->FindVirtualMethod(name, signature);
3221 }
3222 if (resolved == NULL) {
3223 ThrowNoSuchMethodError(is_direct, klass, name, signature);
3224 return NULL;
3225 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003226 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003227 dex_cache->SetResolvedMethod(method_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003228 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003229}
3230
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003231Field* ClassLinker::ResolveField(const DexFile& dex_file,
3232 uint32_t field_idx,
3233 DexCache* dex_cache,
3234 const ClassLoader* class_loader,
3235 bool is_static) {
3236 Field* resolved = dex_cache->GetResolvedField(field_idx);
3237 if (resolved != NULL) {
3238 return resolved;
3239 }
3240 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3241 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3242 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003243 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003244 return NULL;
3245 }
3246
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003247 if (is_static) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003248 resolved = klass->FindStaticField(dex_cache, field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003249 } else {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003250 resolved = klass->FindInstanceField(dex_cache, field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003251 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003252
3253 if (resolved == NULL) {
3254 const char* name = dex_file.GetFieldName(field_id);
3255 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3256 if (is_static) {
3257 resolved = klass->FindStaticField(name, type);
3258 } else {
3259 resolved = klass->FindInstanceField(name, type);
3260 }
3261 if (resolved == NULL) {
3262 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
3263 return NULL;
3264 }
Ian Rogersb067ac22011-12-13 18:05:09 -08003265 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003266 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08003267 return resolved;
3268}
3269
3270Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
3271 uint32_t field_idx,
3272 DexCache* dex_cache,
3273 const ClassLoader* class_loader) {
3274 Field* resolved = dex_cache->GetResolvedField(field_idx);
3275 if (resolved != NULL) {
3276 return resolved;
3277 }
3278 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3279 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3280 if (klass == NULL) {
3281 DCHECK(Thread::Current()->IsExceptionPending());
3282 return NULL;
3283 }
3284
3285 const char* name = dex_file.GetFieldName(field_id);
3286 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3287 resolved = klass->FindField(name, type);
3288 if (resolved != NULL) {
3289 dex_cache->SetResolvedField(field_idx, resolved);
3290 } else {
3291 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003292 }
3293 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07003294}
3295
Ian Rogersad25ac52011-10-04 19:13:33 -07003296const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
3297 Class* declaring_class = referrer->GetDeclaringClass();
3298 DexCache* dex_cache = declaring_class->GetDexCache();
3299 const DexFile& dex_file = FindDexFile(dex_cache);
3300 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3301 return dex_file.GetShorty(method_id.proto_idx_);
3302}
3303
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003304void ClassLinker::DumpAllClasses(int flags) const {
3305 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3306 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3307 std::vector<Class*> all_classes;
3308 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003309 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003310 typedef Table::const_iterator It; // TODO: C++0x auto
3311 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3312 all_classes.push_back(it->second);
3313 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003314 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3315 all_classes.push_back(it->second);
3316 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003317 }
3318
3319 for (size_t i = 0; i < all_classes.size(); ++i) {
3320 all_classes[i]->DumpClass(std::cerr, flags);
3321 }
3322}
3323
Elliott Hughescac6cc72011-11-03 20:31:21 -07003324void ClassLinker::DumpForSigQuit(std::ostream& os) const {
3325 MutexLock mu(classes_lock_);
3326 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3327 << classes_.size() << " allocated classes\n";
3328}
3329
Elliott Hughese27955c2011-08-26 15:21:24 -07003330size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003331 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003332 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003333}
3334
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003335pid_t ClassLinker::GetClassesLockOwner() {
3336 return classes_lock_.GetOwner();
3337}
3338
3339pid_t ClassLinker::GetDexLockOwner() {
3340 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003341}
3342
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003343void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3344 DCHECK(!init_done_);
3345
3346 DCHECK(klass != NULL);
3347 DCHECK(klass->GetClassLoader() == NULL);
3348
3349 DCHECK(class_roots_ != NULL);
3350 DCHECK(class_roots_->Get(class_root) == NULL);
3351 class_roots_->Set(class_root, klass);
3352}
3353
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003354} // namespace art