blob: ac2f4f1647ca1297cb32857fa9592114139d2325 [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 Carlstrom1f870082011-08-23 16:02:11 -070043#include "runtime.h"
Ian Rogers466bb252011-10-14 03:29:56 -070044#include "runtime_support.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070045#include "ScopedLocalRef.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070046#include "space.h"
Brian Carlstrom40381fb2011-10-19 14:13:40 -070047#include "stack_indirect_reference_table.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070048#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070049#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070050#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070051#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070052
53namespace art {
54
Elliott Hughes4a2b4172011-09-20 17:08:25 -070055namespace {
56
Elliott Hughes362f9bc2011-10-17 18:56:41 -070057void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070058void ThrowNoClassDefFoundError(const char* fmt, ...) {
59 va_list args;
60 va_start(args, fmt);
61 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
62 va_end(args);
63}
64
Elliott Hughes362f9bc2011-10-17 18:56:41 -070065void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughese555dc02011-09-25 10:46:35 -070066void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070067 va_list args;
68 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070069 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070070 va_end(args);
71}
72
Elliott Hughes362f9bc2011-10-17 18:56:41 -070073void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070074void ThrowLinkageError(const char* fmt, ...) {
75 va_list args;
76 va_start(args, fmt);
77 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
78 va_end(args);
79}
80
Ian Rogers9f1ab122011-12-12 08:52:43 -080081void ThrowNoSuchMethodError(bool is_direct, Class* c, const StringPiece& name,
82 const StringPiece& signature) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080083 ClassHelper kh(c);
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070084 std::ostringstream msg;
Ian Rogers9f1ab122011-12-12 08:52:43 -080085 msg << "no " << (is_direct ? "direct" : "virtual") << " method " << name << "." << signature
86 << " in class " << kh.GetDescriptor() << " or its superclasses";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080087 std::string location(kh.GetLocation());
88 if (!location.empty()) {
89 msg << " (defined in " << location << ")";
Elliott Hughescc5f9a92011-09-28 19:17:29 -070090 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070091 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070092}
93
Ian Rogersb067ac22011-12-13 18:05:09 -080094void ThrowNoSuchFieldError(const StringPiece& scope, Class* c, const StringPiece& type,
Ian Rogers9f1ab122011-12-12 08:52:43 -080095 const StringPiece& name) {
96 ClassHelper kh(c);
97 std::ostringstream msg;
Ian Rogersb067ac22011-12-13 18:05:09 -080098 msg << "no " << scope << "field " << name << " of type " << type
Ian Rogers9f1ab122011-12-12 08:52:43 -080099 << " in class " << kh.GetDescriptor() << " or its superclasses";
100 std::string location(kh.GetLocation());
101 if (!location.empty()) {
102 msg << " (defined in " << location << ")";
103 }
104 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchFieldError;", msg.str().c_str());
105}
106
Ian Rogerscab01012012-01-10 17:35:46 -0800107void ThrowNullPointerException(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
108void ThrowNullPointerException(const char* fmt, ...) {
109 va_list args;
110 va_start(args, fmt);
111 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NullPointerException;", fmt, args);
112 va_end(args);
113}
114
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700115void ThrowEarlierClassFailure(Class* c) {
116 /*
117 * The class failed to initialize on a previous attempt, so we want to throw
118 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
119 * failed in verification, in which case v2 5.4.1 says we need to re-throw
120 * the previous error.
121 */
122 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
123
124 if (c->GetVerifyErrorClass() != NULL) {
125 // TODO: change the verifier to store an _instance_, with a useful detail message?
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800126 ClassHelper ve_ch(c->GetVerifyErrorClass());
127 std::string error_descriptor(ve_ch.GetDescriptor());
128 Thread::Current()->ThrowNewException(error_descriptor.c_str(), PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700129 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800130 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700131 }
132}
133
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700134void WrapExceptionInInitializer() {
135 JNIEnv* env = Thread::Current()->GetJniEnv();
136
137 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
138 CHECK(cause.get() != NULL);
139
140 env->ExceptionClear();
141
142 // TODO: add java.lang.Error to JniConstants?
143 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
144 CHECK(error_class.get() != NULL);
145 if (env->IsInstanceOf(cause.get(), error_class.get())) {
146 // We only wrap non-Error exceptions; an Error can just be used as-is.
147 env->Throw(cause.get());
148 return;
149 }
150
151 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
152 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
153 CHECK(eiie_class.get() != NULL);
154
155 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
156 CHECK(mid != NULL);
157
158 ScopedLocalRef<jthrowable> eiie(env,
159 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
160 env->Throw(eiie.get());
161}
162
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800163static size_t Hash(const char* s) {
164 // This is the java.lang.String hashcode for convenience, not interoperability.
165 size_t hash = 0;
166 for (; *s != '\0'; ++s) {
167 hash = hash * 31 + *s;
168 }
169 return hash;
170}
171
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700172} // namespace
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700173
Elliott Hughes418d20f2011-09-22 14:00:39 -0700174const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700175 "Ljava/lang/Class;",
176 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700177 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700178 "[Ljava/lang/Object;",
179 "Ljava/lang/String;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700180 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700181 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700182 "Ljava/lang/reflect/Field;",
183 "Ljava/lang/reflect/Method;",
Ian Rogers466bb252011-10-14 03:29:56 -0700184 "Ljava/lang/reflect/Proxy;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700185 "Ljava/lang/ClassLoader;",
186 "Ldalvik/system/BaseDexClassLoader;",
187 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700188 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700189 "Z",
190 "B",
191 "C",
192 "D",
193 "F",
194 "I",
195 "J",
196 "S",
197 "V",
198 "[Z",
199 "[B",
200 "[C",
201 "[D",
202 "[F",
203 "[I",
204 "[J",
205 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700206 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700207};
208
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800209ClassLinker* ClassLinker::Create(const std::string& boot_class_path, InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700210 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800211 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700212 class_linker->Init(boot_class_path);
213 return class_linker.release();
214}
215
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800216ClassLinker* ClassLinker::Create(InternTable* intern_table) {
217 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700218 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700219 return class_linker.release();
220}
221
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800222ClassLinker::ClassLinker(InternTable* intern_table)
223 : dex_lock_("ClassLinker dex lock"),
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700224 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700225 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700226 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700227 init_done_(false),
228 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700229 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700230}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700231
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700232void CreateClassPath(const std::string& class_path,
233 std::vector<const DexFile*>& class_path_vector) {
234 std::vector<std::string> parsed;
235 Split(class_path, ':', parsed);
236 for (size_t i = 0; i < parsed.size(); ++i) {
237 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700238 if (dex_file == NULL) {
239 LOG(WARNING) << "Failed to open dex file " << parsed[i];
240 } else {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700241 class_path_vector.push_back(dex_file);
242 }
243 }
244}
245
246void ClassLinker::Init(const std::string& boot_class_path) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800247 VLOG(startup) << "ClassLinker::InitFrom entering boot_class_path=" << boot_class_path;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700248
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700249 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700250
Elliott Hughes30646832011-10-13 16:59:46 -0700251 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700252 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
253 CHECK(java_lang_Class.get() != NULL);
254 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700255 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700256 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700257
Elliott Hughes418d20f2011-09-22 14:00:39 -0700258 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700259 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
260 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700261
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700262 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700263 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
264 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700265 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700266 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700267 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700268
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700269 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700270 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
271 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700272
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700273 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700274 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700275
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700276 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700277 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
278 char_array_class->SetComponentType(char_class.get());
279 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700280
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700281 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700282 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
283 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700284 java_lang_String->SetObjectSize(sizeof(String));
285 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400286
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700287 // Create storage for root classes, save away our work so far (requires
288 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700289 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700290 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700291 SetClassRoot(kJavaLangClass, java_lang_Class.get());
292 SetClassRoot(kJavaLangObject, java_lang_Object.get());
293 SetClassRoot(kClassArrayClass, class_array_class.get());
294 SetClassRoot(kObjectArrayClass, object_array_class.get());
295 SetClassRoot(kCharArrayClass, char_array_class.get());
296 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700297
298 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700299 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
300 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
301 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
302 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
303 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
304 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
305 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
306 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700307
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700308 // Create array interface entries to populate once we can load system classes
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700309 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700310
311 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700312 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700313 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700314 IntArray::SetArrayClass(int_array_class.get());
315 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700316
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700317 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700318
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700319 // setup boot_class_path_ and register class_path now that we can
320 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700321 std::vector<const DexFile*> boot_class_path_vector;
322 CreateClassPath(boot_class_path, boot_class_path_vector);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700323 CHECK_NE(0U, boot_class_path_vector.size());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700324 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
325 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700326 CHECK(dex_file != NULL);
327 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700328 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700329
Elliott Hughes80609252011-09-23 17:24:51 -0700330 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700331 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700332 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700333 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700334 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700335 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
336
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700337 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
338 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700339 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700340 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700341 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700342 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700343
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700344 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700345 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700346 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700347 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700348 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700349 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700350
351 // now we can use FindSystemClass
352
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700353 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700354 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700355 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700356
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700357 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700358 java_lang_Object->SetStatus(Class::kStatusNotReady);
359 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700360 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700361 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
362 java_lang_String->SetStatus(Class::kStatusNotReady);
363 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700364 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700365 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
366
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700367 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700368 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
369 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
370
371 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
372 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
373
374 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700375 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700376
377 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
378 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
379
380 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700381 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700382
383 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
384 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
385
386 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
387 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
388
389 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
390 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
391
Elliott Hughes418d20f2011-09-22 14:00:39 -0700392 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700393 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700394
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700395 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700396 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700397
398 // Setup the single, global copies of "interfaces" and "iftable"
399 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
400 CHECK(java_lang_Cloneable != NULL);
401 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
402 CHECK(java_io_Serializable != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700403 // We assume that Cloneable/Serializable don't have superinterfaces --
404 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700405 // supers as well.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800406 array_iftable_->Set(0, AllocInterfaceEntry(java_lang_Cloneable));
407 array_iftable_->Set(1, AllocInterfaceEntry(java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700408
Elliott Hughes418d20f2011-09-22 14:00:39 -0700409 // Sanity check Class[] and Object[]'s interfaces
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800410 ClassHelper kh(class_array_class.get(), this);
411 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
412 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
413 kh.ChangeClass(object_array_class.get());
414 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
415 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
Elliott Hughes80609252011-09-23 17:24:51 -0700416 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700417 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700418 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700419 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700420
Elliott Hughes80609252011-09-23 17:24:51 -0700421 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
422 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700423 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700424
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700425 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700426 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700427 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700428
429 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700430 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700431 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700432
Ian Rogers466bb252011-10-14 03:29:56 -0700433 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
434
435 // Create java.lang.reflect.Proxy root
436 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
437 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
438
Brian Carlstrom1f870082011-08-23 16:02:11 -0700439 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700440 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
441 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700442 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700443 java_lang_ref_FinalizerReference->SetAccessFlags(
444 java_lang_ref_FinalizerReference->GetAccessFlags() |
445 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700446 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700447 java_lang_ref_PhantomReference->SetAccessFlags(
448 java_lang_ref_PhantomReference->GetAccessFlags() |
449 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700450 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700451 java_lang_ref_SoftReference->SetAccessFlags(
452 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700453 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700454 java_lang_ref_WeakReference->SetAccessFlags(
455 java_lang_ref_WeakReference->GetAccessFlags() |
456 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700457
Brian Carlstromaded5f72011-10-07 17:15:04 -0700458 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700459 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700460 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700461 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
462
463 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
464 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
465 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
466
467 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
468 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
469 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
470 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
471
472 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700473 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
474 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700475 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700476
Brian Carlstroma663ea52011-08-19 23:33:41 -0700477 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700478
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800479 VLOG(startup) << "ClassLinker::InitFrom exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700480}
481
482void ClassLinker::FinishInit() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800483 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700484
485 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700486 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700487 // as the types of the field can't be resolved prior to the runtime being
488 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700489 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700490 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700491 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
492
Elliott Hughesadb460d2011-10-05 17:02:34 -0700493 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
494
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800495 const DexFile& java_lang_dex = FindDexFile(java_lang_ref_Reference->GetDexCache());
496
Brian Carlstrom16192862011-09-12 17:50:06 -0700497 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800498 FieldHelper fh(pendingNext, this);
499 CHECK_STREQ(fh.GetName(), "pendingNext");
500 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
501 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700502
503 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800504 fh.ChangeField(queue);
505 CHECK_STREQ(fh.GetName(), "queue");
506 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
507 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700508
509 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800510 fh.ChangeField(queueNext);
511 CHECK_STREQ(fh.GetName(), "queueNext");
512 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
513 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700514
515 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800516 fh.ChangeField(referent);
517 CHECK_STREQ(fh.GetName(), "referent");
518 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
519 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700520
521 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800522 fh.ChangeField(zombie);
523 CHECK_STREQ(fh.GetName(), "zombie");
524 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
525 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700526
527 Heap::SetReferenceOffsets(referent->GetOffset(),
528 queue->GetOffset(),
529 queueNext->GetOffset(),
530 pendingNext->GetOffset(),
531 zombie->GetOffset());
532
Brian Carlstroma663ea52011-08-19 23:33:41 -0700533 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700534 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700535 ClassRoot class_root = static_cast<ClassRoot>(i);
536 Class* klass = GetClassRoot(class_root);
537 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700538 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700539 // note SetClassRoot does additional validation.
540 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700541 }
542
Elliott Hughes92f14b22011-10-06 12:29:54 -0700543 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700544
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700545 // disable the slow paths in FindClass and CreatePrimitiveClass now
546 // that Object, Class, and Object[] are setup
547 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700548
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800549 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700550}
551
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700552void ClassLinker::RunRootClinits() {
553 Thread* self = Thread::Current();
554 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
555 Class* c = GetClassRoot(ClassRoot(i));
556 if (!c->IsArrayClass() && !c->IsPrimitive()) {
557 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700558 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700559 }
560 }
561}
562
Brian Carlstromd601af82012-01-06 10:15:19 -0800563bool ClassLinker::GenerateOatFile(const std::string& dex_filename,
564 int oat_fd,
565 const std::string& oat_cache_filename) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800566 std::string dex2oat_string("/system/bin/dex2oat");
567#ifndef NDEBUG
568 dex2oat_string += 'd';
569#endif
570 const char* dex2oat = dex2oat_string.c_str();
571
572 const char* class_path = Runtime::Current()->GetClassPath().c_str();
573
574 std::string boot_image_option_string("--boot-image=");
Ian Rogers30fab402012-01-23 15:43:46 -0800575 boot_image_option_string += Heap::GetSpaces()[0]->AsImageSpace()->GetImageFilename();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800576 const char* boot_image_option = boot_image_option_string.c_str();
577
578 std::string dex_file_option_string("--dex-file=");
Brian Carlstromd601af82012-01-06 10:15:19 -0800579 dex_file_option_string += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800580 const char* dex_file_option = dex_file_option_string.c_str();
581
Brian Carlstromd601af82012-01-06 10:15:19 -0800582 std::string oat_fd_option_string("--oat-fd=");
Brian Carlstrom866c8622012-01-06 16:35:13 -0800583 StringAppendF(&oat_fd_option_string, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800584 const char* oat_fd_option = oat_fd_option_string.c_str();
585
586 std::string oat_name_option_string("--oat-name=");
587 oat_name_option_string += oat_cache_filename;
588 const char* oat_name_option = oat_name_option_string.c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800589
jeffhao262bf462011-10-20 18:36:32 -0700590 // fork and exec dex2oat
591 pid_t pid = fork();
592 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800593 // no allocation allowed between fork and exec
Ian Rogers725aee52012-01-11 11:56:56 -0800594
595 // change process groups, so we don't get reaped by ProcessManager
596 setpgid(0, 0);
597
jeffhao10037c82012-01-23 15:06:23 -0800598 VLOG(class_linker) << dex2oat
599 << " --runtime-arg -Xms64m"
600 << " --runtime-arg -Xmx64m"
601 << " --runtime-arg -classpath"
602 << " --runtime-arg " << class_path
603 << " " << boot_image_option
604 << " " << dex_file_option
605 << " " << oat_fd_option
606 << " " << oat_name_option;
607
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800608 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700609 "--runtime-arg", "-Xms64m",
610 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500611 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800612 "--runtime-arg", class_path,
613 boot_image_option,
614 dex_file_option,
Brian Carlstromd601af82012-01-06 10:15:19 -0800615 oat_fd_option,
616 oat_name_option,
jeffhao262bf462011-10-20 18:36:32 -0700617 NULL);
618
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800619 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
Brian Carlstromd601af82012-01-06 10:15:19 -0800620 return false;
jeffhao262bf462011-10-20 18:36:32 -0700621 } else {
622 // wait for dex2oat to finish
623 int status;
624 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
625 if (got_pid != pid) {
626 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
Brian Carlstromd601af82012-01-06 10:15:19 -0800627 return false;
jeffhao262bf462011-10-20 18:36:32 -0700628 }
629 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800630 LOG(ERROR) << dex2oat << " failed with dex-file=" << dex_filename;
631 return false;
jeffhao262bf462011-10-20 18:36:32 -0700632 }
633 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800634 return true;
jeffhao262bf462011-10-20 18:36:32 -0700635}
636
Brian Carlstrom866c8622012-01-06 16:35:13 -0800637void ClassLinker::RegisterOatFile(const OatFile& oat_file) {
638 MutexLock mu(dex_lock_);
639 RegisterOatFileLocked(oat_file);
640}
641
642void ClassLinker::RegisterOatFileLocked(const OatFile& oat_file) {
643 dex_lock_.AssertHeld();
644 oat_files_.push_back(&oat_file);
645}
646
Ian Rogers30fab402012-01-23 15:43:46 -0800647OatFile* ClassLinker::OpenOat(const ImageSpace* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700648 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700649 const Runtime* runtime = Runtime::Current();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700650 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800651 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
652 // check the down cast
653 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700654 std::string oat_filename;
655 oat_filename += runtime->GetHostPrefix();
656 oat_filename += oat_location->ToModifiedUtf8();
Ian Rogers30fab402012-01-23 15:43:46 -0800657 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBegin());
658 VLOG(startup) << "ClassLinker::OpenOat entering oat_filename=" << oat_filename;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700659 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700660 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700661 return NULL;
662 }
663 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
664 uint32_t image_oat_checksum = image_header.GetOatChecksum();
665 if (oat_checksum != image_oat_checksum) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800666 LOG(ERROR) << "Failed to match oat file checksum " << std::hex << oat_checksum
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700667 << " to expected oat checksum " << std::hex << oat_checksum
668 << " in image";
669 return NULL;
670 }
Brian Carlstrom866c8622012-01-06 16:35:13 -0800671 RegisterOatFileLocked(*oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800672 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700673 return oat_file;
674}
675
Brian Carlstromae826982011-11-09 01:33:42 -0800676const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
677 for (size_t i = 0; i < oat_files_.size(); i++) {
678 const OatFile* oat_file = oat_files_[i];
679 DCHECK(oat_file != NULL);
Ian Rogers7fe2c692011-12-06 16:35:59 -0800680 if (oat_file->GetOatDexFile(dex_file.GetLocation(), false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800681 return oat_file;
682 }
683 }
684 return NULL;
685}
686
Brian Carlstromd601af82012-01-06 10:15:19 -0800687class LockedFd {
688 public:
689 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
690 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
691 if (fd == -1) {
692 PLOG(ERROR) << "Failed to open file '" << name << "'";
693 return NULL;
694 }
695 fchmod(fd, mode);
696
697 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
698 // try to lock non-blocking so we can log if we need may need to block
699 int result = flock(fd, LOCK_EX | LOCK_NB);
700 if (result == -1) {
701 LOG(WARNING) << "sleeping while locking file " << name;
702 // retry blocking
703 result = flock(fd, LOCK_EX);
704 }
705 if (result == -1) {
706 PLOG(ERROR) << "Failed to lock file '" << name << "'";
707 close(fd);
708 return NULL;
709 }
710 return new LockedFd(fd);
711 }
712
713 int GetFd() const {
714 return fd_;
715 }
716
717 ~LockedFd() {
718 if (fd_ != -1) {
719 int result = flock(fd_, LOCK_UN);
720 if (result == -1) {
721 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
722 }
723 close(fd_);
724 }
725 }
726
727 private:
728 explicit LockedFd(int fd) : fd_(fd) {}
729
730 int fd_;
731};
732
Brian Carlstromae826982011-11-09 01:33:42 -0800733const OatFile* ClassLinker::FindOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700734 MutexLock mu(dex_lock_);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800735 const OatFile* open_oat_file = FindOpenedOatFileForDexFile(dex_file);
736 if (open_oat_file != NULL) {
737 return open_oat_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800738 }
739
Brian Carlstromd601af82012-01-06 10:15:19 -0800740 std::string oat_filename(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
Brian Carlstrom866c8622012-01-06 16:35:13 -0800741 open_oat_file = FindOpenedOatFileFromOatLocation(oat_filename);
742 if (open_oat_file != NULL) {
743 return open_oat_file;
744 }
745
Brian Carlstromd601af82012-01-06 10:15:19 -0800746 while (true) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800747 UniquePtr<const OatFile> oat_file(FindOatFileFromOatLocation(oat_filename));
748 if (oat_file.get() != NULL) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800749 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
750 if (dex_file.GetHeader().checksum_ == oat_dex_file->GetDexFileChecksum()) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800751 RegisterOatFileLocked(*oat_file.get());
752 return oat_file.release();
Brian Carlstromd601af82012-01-06 10:15:19 -0800753 }
754 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
755 << " checksum mismatch with " << dex_file.GetLocation() << " --- regenerating";
756 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
757 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
758 }
759 // Fall through...
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700760 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800761 // Try to generate oat file if it wasn't found or was obsolete.
762 // Note we can be racing with another runtime to do this.
763 std::string oat_cache_filename(GetArtCacheFilenameOrDie(oat_filename));
764 UniquePtr<LockedFd> locked_fd(LockedFd::CreateAndLock(oat_cache_filename, 0644));
765 if (locked_fd.get() == NULL) {
766 LOG(ERROR) << "Failed to create and lock oat file " << oat_cache_filename;
767 return NULL;
Elliott Hughes234da572011-11-03 22:13:06 -0700768 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800769 // Check to see if the fd we opened and locked matches the file in
770 // the filesystem. If they don't, then somebody else unlinked ours
771 // and created a new file, and we need to use that one instead. (If
772 // we caught them between the unlink and the create, we'll get an
773 // ENOENT from the file stat.)
774 struct stat fd_stat;
775 int fd_stat_result = fstat(locked_fd->GetFd(), &fd_stat);
776 if (fd_stat_result != 0) {
777 PLOG(ERROR) << "Failed to fstat file descriptor of oat file " << oat_cache_filename;
778 return NULL;
779 }
780 struct stat file_stat;
781 int file_stat_result = stat(oat_cache_filename.c_str(), &file_stat);
782 if (file_stat_result != 0
783 || fd_stat.st_dev != file_stat.st_dev
784 || fd_stat.st_ino != file_stat.st_ino) {
785 LOG(INFO) << "Opened oat file " << oat_cache_filename << " is stale; sleeping and retrying";
786 usleep(250 * 1000); // if something is hosed, don't peg machine
787 continue;
788 }
789
790 // We have the correct file open and locked. If the file size is
791 // zero, then it was just created by us and we can generate its
792 // contents. If not, someone else created it. Either way, we'll
793 // loop to retry opening the file.
794 if (fd_stat.st_size == 0) {
795 bool success = GenerateOatFile(dex_file.GetLocation(),
796 locked_fd->GetFd(),
797 oat_cache_filename);
798 if (!success) {
799 LOG(ERROR) << "Failed to generate oat file " << oat_cache_filename;
800 return NULL;
801 }
802 }
jeffhao262bf462011-10-20 18:36:32 -0700803 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800804 // Not reached
Brian Carlstromaded5f72011-10-07 17:15:04 -0700805}
806
Brian Carlstromae826982011-11-09 01:33:42 -0800807const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700808 for (size_t i = 0; i < oat_files_.size(); i++) {
809 const OatFile* oat_file = oat_files_[i];
810 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800811 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700812 return oat_file;
813 }
814 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700815 return NULL;
816}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700817
Brian Carlstromae826982011-11-09 01:33:42 -0800818const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800819 const OatFile* oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700820 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800821 if (oat_location.empty() || oat_location[0] != '/') {
822 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700823 return NULL;
824 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700825
Brian Carlstroma9f19782011-10-13 00:14:47 -0700826 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Elliott Hughes95572412011-12-13 18:14:20 -0800827 std::string cache_location(GetArtCacheFilenameOrDie(oat_location));
Brian Carlstromae826982011-11-09 01:33:42 -0800828 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700829 if (oat_file != NULL) {
830 return oat_file;
831 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700832 oat_file = OatFile::Open(cache_location, "", NULL);
833 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800834 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700835 return NULL;
836 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700837 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700838
Brian Carlstromae826982011-11-09 01:33:42 -0800839 CHECK(oat_file != NULL) << oat_location;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700840 return oat_file;
841}
842
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700843void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800844 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700845 CHECK(!init_done_);
846
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700847 const std::vector<Space*>& spaces = Heap::GetSpaces();
848 for (size_t i = 0; i < spaces.size(); i++) {
Ian Rogers30fab402012-01-23 15:43:46 -0800849 if (spaces[i]->IsImageSpace()) {
850 ImageSpace* space = spaces[i]->AsImageSpace();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700851 OatFile* oat_file = OpenOat(space);
852 CHECK(oat_file != NULL) << "Failed to open oat file for image";
853 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
854 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
855
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800856 if (i == 0) {
857 // Special case of setting up the String class early so that we can test arbitrary objects
858 // as being Strings or not
Ian Rogers30fab402012-01-23 15:43:46 -0800859 Class* java_lang_String = space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800860 ->AsObjectArray<Class>()->Get(kJavaLangString);
861 String::SetClass(java_lang_String);
862 }
863
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700864 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
865 static_cast<uint32_t>(dex_caches->GetLength()));
866 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700867 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800868 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom89521892011-12-07 22:05:07 -0800869 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
870 const DexFile* dex_file = oat_dex_file->OpenDexFile();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700871 if (dex_file == NULL) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800872 LOG(FATAL) << "Failed to open dex file " << dex_file_location
873 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700874 }
875
Brian Carlstromaded5f72011-10-07 17:15:04 -0700876 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700877
Brian Carlstromdf143242011-10-10 18:05:34 -0700878 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700879 }
880 }
881 }
882
Brian Carlstroma663ea52011-08-19 23:33:41 -0700883 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
884 DCHECK(heap_bitmap != NULL);
885
Brian Carlstroma663ea52011-08-19 23:33:41 -0700886 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700887 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700888
889 // reinit class_roots_
Ian Rogers30fab402012-01-23 15:43:46 -0800890 Object* class_roots_object =
891 spaces[0]->AsImageSpace()->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700892 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700893
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800894 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700895 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
896 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800897 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700898 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700899 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700900 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
901 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
902 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
903 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
904 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
905 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
906 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
907 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700908 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700909 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700910
911 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700912
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800913 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700914}
915
Brian Carlstrom78128a62011-09-15 17:21:19 -0700916void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700917 DCHECK(obj != NULL);
918 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700919 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700920
Elliott Hughesdbb40792011-11-18 17:05:22 -0800921 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700922 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700923 return;
924 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700925 if (obj->IsClass()) {
926 // restore class to ClassLinker::classes_ table
927 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800928 ClassHelper kh(klass, class_linker);
Brian Carlstrom07bb8552012-01-18 22:10:50 -0800929 Class* existing = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
930 DCHECK(existing == NULL) << kh.GetDescriptor();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700931 return;
932 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700933}
934
935// Keep in sync with InitCallback. Anything we visit, we need to
936// reinit references to when reinitializing a ClassLinker from a
937// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700938void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
939 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700940
941 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700942 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700943 }
944
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700945 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700946 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700947 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700948 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700949 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700950 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700951 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700952 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700953
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700954 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700955}
956
Elliott Hughesa2155262011-11-16 16:26:58 -0800957void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
958 MutexLock mu(classes_lock_);
959 typedef Table::const_iterator It; // TODO: C++0x auto
960 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
961 if (!visitor(it->second, arg)) {
962 return;
963 }
964 }
965 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
966 if (!visitor(it->second, arg)) {
967 return;
968 }
969 }
970}
971
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700972ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700973 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700974 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700975 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700976 BooleanArray::ResetArrayClass();
977 ByteArray::ResetArrayClass();
978 CharArray::ResetArrayClass();
979 DoubleArray::ResetArrayClass();
980 FloatArray::ResetArrayClass();
981 IntArray::ResetArrayClass();
982 LongArray::ResetArrayClass();
983 ShortArray::ResetArrayClass();
984 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700985 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700986 STLDeleteElements(&boot_class_path_);
987 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700988}
989
990DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700991 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
992 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700993 return NULL;
994 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700995 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
996 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700997 return NULL;
998 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700999 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
1000 if (strings.get() == NULL) {
1001 return NULL;
1002 }
1003 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
1004 if (types.get() == NULL) {
1005 return NULL;
1006 }
1007 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
1008 if (methods.get() == NULL) {
1009 return NULL;
1010 }
1011 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
1012 if (fields.get() == NULL) {
1013 return NULL;
1014 }
1015 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
1016 if (code_and_direct_methods.get() == NULL) {
1017 return NULL;
1018 }
1019 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
1020 if (initialized_static_storage.get() == NULL) {
1021 return NULL;
1022 }
1023
1024 dex_cache->Init(location.get(),
1025 strings.get(),
1026 types.get(),
1027 methods.get(),
1028 fields.get(),
1029 code_and_direct_methods.get(),
1030 initialized_static_storage.get());
1031 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001032}
1033
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001034CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
1035 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -07001036}
1037
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001038InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
1039 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001040 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
1041 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001042 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001043 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001044}
1045
Brian Carlstrom4873d462011-08-21 15:23:39 -07001046Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
1047 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001048 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001049 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001050 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001051 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001052}
1053
Brian Carlstrom4873d462011-08-21 15:23:39 -07001054Class* ClassLinker::AllocClass(size_t class_size) {
1055 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001056}
1057
Jesse Wilson35baaab2011-08-10 16:18:03 -04001058Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001059 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -07001060}
1061
1062Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001063 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001064}
1065
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001066ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
1067 return ObjectArray<StackTraceElement>::Alloc(
1068 GetClassRoot(kJavaLangStackTraceElementArrayClass),
1069 length);
1070}
1071
Brian Carlstromaded5f72011-10-07 17:15:04 -07001072Class* EnsureResolved(Class* klass) {
1073 DCHECK(klass != NULL);
1074 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -07001075 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001076 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001077 ObjectLock lock(klass);
1078 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001079 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001080 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001081 PrettyDescriptor(klass).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001082 return NULL;
1083 }
1084 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001085 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001086 lock.Wait();
1087 }
1088 }
1089 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001090 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001091 return NULL;
1092 }
1093 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001094 CHECK(klass->IsResolved()) << PrettyClass(klass);
1095 CHECK(!self->IsExceptionPending())
1096 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
1097 return klass;
1098}
1099
Elliott Hughesdb7d5e92011-12-16 18:47:37 -08001100Class* ClassLinker::FindSystemClass(const char* descriptor) {
1101 return FindClass(descriptor, NULL);
1102}
1103
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001104Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001105 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001106 Thread* self = Thread::Current();
1107 DCHECK(self != NULL);
1108 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001109 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001110 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1111 // for primitive classes that aren't backed by dex files.
1112 return FindPrimitiveClass(descriptor[0]);
1113 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001114 // Find the class in the loaded classes table.
1115 Class* klass = LookupClass(descriptor, class_loader);
1116 if (klass != NULL) {
1117 return EnsureResolved(klass);
1118 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001119 // Class is not yet loaded.
1120 if (descriptor[0] == '[') {
1121 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001122
Jesse Wilson47daf872011-11-23 11:42:45 -05001123 } else if (class_loader == NULL) {
1124 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1125 if (pair.second != NULL) {
1126 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1127 }
1128
1129 } else if (ClassLoader::UseCompileTimeClassPath()) {
1130 // first try the boot class path
1131 Class* system_class = FindSystemClass(descriptor);
1132 if (system_class != NULL) {
1133 return system_class;
1134 }
1135 CHECK(self->IsExceptionPending());
1136 self->ClearException();
1137
1138 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001139 const std::vector<const DexFile*>& class_path
1140 = ClassLoader::GetCompileTimeClassPath(class_loader);
1141 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001142 if (pair.second != NULL) {
1143 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001144 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001145
1146 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001147 std::string class_name_string(DescriptorToDot(descriptor));
Jesse Wilson47daf872011-11-23 11:42:45 -05001148 ScopedThreadStateChange(self, Thread::kNative);
Elliott Hughes748382f2012-01-26 18:07:38 -08001149 JNIEnv* env = self->GetJniEnv();
Jesse Wilson47daf872011-11-23 11:42:45 -05001150 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1151 CHECK(c.get() != NULL);
1152 // TODO: cache method?
1153 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1154 CHECK(mid != NULL);
1155 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1156 if (class_name_object.get() == NULL) {
1157 return NULL;
1158 }
1159 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
Ian Rogers761bfa82012-01-11 10:14:05 -08001160 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid,
1161 class_name_object.get()));
Elliott Hughes748382f2012-01-26 18:07:38 -08001162 if (env->ExceptionOccurred()) {
1163 // If the ClassLoader threw, pass that exception up.
1164 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001165 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001166 // broken loader - throw NPE to be compatible with Dalvik
1167 ThrowNullPointerException("ClassLoader.loadClass returned null for %s",
1168 class_name_string.c_str());
1169 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001170 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08001171 // success, return Class*
Ian Rogers6b0870d2011-12-15 19:38:12 -08001172 return Decode<Class*>(env, result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001173 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001174 }
1175
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001176 ThrowNoClassDefFoundError("Class %s not found", PrintableString(StringPiece(descriptor)).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001177 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001178}
1179
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001180Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001181 const ClassLoader* class_loader,
1182 const DexFile& dex_file,
1183 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001184 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001185 // Load the class from the dex file.
1186 if (!init_done_) {
1187 // finish up init of hand crafted class_roots_
1188 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001189 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001190 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001191 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001192 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001193 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001194 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001195 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001196 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001197 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001198 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001199 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001200 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001201 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001202 }
1203 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001204 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001205 }
1206 klass->SetDexCache(FindDexCache(dex_file));
1207 LoadClass(dex_file, dex_class_def, klass, class_loader);
1208 // Check for a pending exception during load
1209 Thread* self = Thread::Current();
1210 if (self->IsExceptionPending()) {
1211 return NULL;
1212 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001213 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001214 klass->SetClinitThreadId(self->GetTid());
1215 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001216 Class* existing = InsertClass(descriptor, klass.get(), false);
1217 if (existing != NULL) {
1218 // We failed to insert because we raced with another thread.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001219 klass->SetClinitThreadId(0);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001220 klass.reset(existing);
1221 return EnsureResolved(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001222 }
1223 // Finish loading (if necessary) by finding parents
1224 CHECK(!klass->IsLoaded());
1225 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1226 // Loading failed.
1227 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001228 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001229 lock.NotifyAll();
1230 return NULL;
1231 }
1232 CHECK(klass->IsLoaded());
1233 // Link the class (if necessary)
1234 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001235 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001236 // Linking failed.
1237 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001238 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001239 lock.NotifyAll();
1240 return NULL;
1241 }
1242 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001243
1244 /*
1245 * We send CLASS_PREPARE events to the debugger from here. The
1246 * definition of "preparation" is creating the static fields for a
1247 * class and initializing them to the standard default values, but not
1248 * executing any code (that comes later, during "initialization").
1249 *
1250 * We did the static preparation in LinkClass.
1251 *
1252 * The class has been prepared and resolved but possibly not yet verified
1253 * at this point.
1254 */
1255 Dbg::PostClassPrepare(klass.get());
1256
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001257 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001258}
1259
Brian Carlstrom4873d462011-08-21 15:23:39 -07001260// Precomputes size that will be needed for Class, matching LinkStaticFields
1261size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1262 const DexFile::ClassDef& dex_class_def) {
1263 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001264 size_t num_ref = 0;
1265 size_t num_32 = 0;
1266 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001267 if (class_data != NULL) {
1268 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1269 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001270 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001271 char c = descriptor[0];
1272 if (c == 'L' || c == '[') {
1273 num_ref++;
1274 } else if (c == 'J' || c == 'D') {
1275 num_64++;
1276 } else {
1277 num_32++;
1278 }
1279 }
1280 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001281 // start with generic class data
1282 size_t size = sizeof(Class);
1283 // follow with reference fields which must be contiguous at start
1284 size += (num_ref * sizeof(uint32_t));
1285 // if there are 64-bit fields to add, make sure they are aligned
1286 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1287 if (num_32 != 0) {
1288 // use an available 32-bit field for padding
1289 num_32--;
1290 }
1291 size += sizeof(uint32_t); // either way, we are adding a word
1292 DCHECK_EQ(size, RoundUp(size, 8));
1293 }
1294 // tack on any 64-bit fields now that alignment is assured
1295 size += (num_64 * sizeof(uint64_t));
1296 // tack on any remaining 32-bit fields
1297 size += (num_32 * sizeof(uint32_t));
1298 return size;
1299}
1300
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001301void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001302 // Every kind of method should at least get an invoke stub from the oat_method.
1303 // non-abstract methods also get their code pointers.
1304 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001305 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001306
1307 if (method->IsAbstract()) {
1308 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1309 return;
1310 }
1311 if (method->IsNative()) {
1312 // unregistering restores the dlsym lookup stub
1313 method->UnregisterNative();
jeffhao26c0a1a2012-01-17 16:28:33 -08001314 }
1315
1316 if (Runtime::Current()->IsMethodTracingActive()) {
1317#if defined(__arm__)
1318 Trace* tracer = Runtime::Current()->GetTracer();
1319 void* trace_stub = reinterpret_cast<void*>(art_trace_entry_from_code);
1320 tracer->SaveAndUpdateCode(method.get(), trace_stub);
1321#else
1322 UNIMPLEMENTED(WARNING);
1323#endif
Brian Carlstrom92827a52011-10-10 15:50:01 -07001324 }
1325}
1326
Brian Carlstromf615a612011-07-23 12:50:34 -07001327void ClassLinker::LoadClass(const DexFile& dex_file,
1328 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001329 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001330 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001331 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001332 CHECK(klass->GetDexCache() != NULL);
1333 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001334 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001335 CHECK(descriptor != NULL);
1336
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001337 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001338 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001339 // Make sure that none of our runtime-only flags are set.
1340 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001341 klass->SetAccessFlags(access_flags);
1342 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001343 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001344 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001345
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001346 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001347
Ian Rogers0571d352011-11-03 19:51:38 -07001348 // Load fields fields.
1349 const byte* class_data = dex_file.GetClassData(dex_class_def);
1350 if (class_data == NULL) {
1351 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001352 }
Ian Rogers0571d352011-11-03 19:51:38 -07001353 ClassDataItemIterator it(dex_file, class_data);
1354 if (it.NumStaticFields() != 0) {
1355 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1356 }
1357 if (it.NumInstanceFields() != 0) {
1358 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1359 }
1360 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1361 SirtRef<Field> sfield(AllocField());
1362 klass->SetStaticField(i, sfield.get());
1363 LoadField(dex_file, it, klass, sfield);
1364 }
1365 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1366 SirtRef<Field> ifield(AllocField());
1367 klass->SetInstanceField(i, ifield.get());
1368 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001369 }
1370
Brian Carlstromaded5f72011-10-07 17:15:04 -07001371 UniquePtr<const OatFile::OatClass> oat_class;
1372 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001373 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001374 if (oat_file != NULL) {
1375 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1376 if (oat_dex_file != NULL) {
1377 uint32_t class_def_index;
1378 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1379 CHECK(found) << descriptor;
1380 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001381 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001382 }
1383 }
1384 }
Ian Rogers0571d352011-11-03 19:51:38 -07001385 // Load methods.
1386 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001387 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001388 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001389 }
Ian Rogers0571d352011-11-03 19:51:38 -07001390 if (it.NumVirtualMethods() != 0) {
1391 // TODO: append direct methods to class object
1392 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001393 }
Ian Rogers0571d352011-11-03 19:51:38 -07001394 size_t method_index = 0;
1395 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1396 SirtRef<Method> method(AllocMethod());
1397 klass->SetDirectMethod(i, method.get());
1398 LoadMethod(dex_file, it, klass, method);
1399 if (oat_class.get() != NULL) {
1400 LinkCode(method, oat_class.get(), method_index);
1401 }
1402 method_index++;
1403 }
1404 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1405 SirtRef<Method> method(AllocMethod());
1406 klass->SetVirtualMethod(i, method.get());
1407 LoadMethod(dex_file, it, klass, method);
1408 if (oat_class.get() != NULL) {
1409 LinkCode(method, oat_class.get(), method_index);
1410 }
1411 method_index++;
1412 }
1413 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001414}
1415
Ian Rogers0571d352011-11-03 19:51:38 -07001416void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1417 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001418 uint32_t field_idx = it.GetMemberIndex();
1419 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001420 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001421 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001422}
1423
Ian Rogers0571d352011-11-03 19:51:38 -07001424void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1425 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001426 uint32_t method_idx = it.GetMemberIndex();
1427 dst->SetDexMethodIndex(method_idx);
1428 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001429 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001430
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001431
1432 StringPiece method_name(dex_file.GetMethodName(method_id));
1433 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001434 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1435 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001436
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001437 if (method_name == "finalize") {
1438 // Create the prototype for a signature of "()V"
1439 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1440 if (void_string_id != NULL) {
1441 const DexFile::TypeId* void_type_id =
1442 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1443 if (void_type_id != NULL) {
1444 std::vector<uint16_t> no_args;
1445 const DexFile::ProtoId* finalizer_proto =
1446 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1447 if (finalizer_proto != NULL) {
1448 // We have the prototype in the dex file
1449 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1450 klass->SetFinalizable();
1451 } else {
1452 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1453 // The Enum class declares a "final" finalize() method to prevent subclasses from
1454 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1455 // subclasses, so we exclude it here.
1456 // We also want to avoid setting the flag on Object, where we know that finalize() is
1457 // empty.
1458 if (klass_descriptor != "Ljava/lang/Object;" &&
1459 klass_descriptor != "Ljava/lang/Enum;") {
1460 klass->SetFinalizable();
1461 }
1462 }
1463 }
1464 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001465 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001466 }
Ian Rogers0571d352011-11-03 19:51:38 -07001467 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001468 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001469
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001470 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1471 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1472 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1473 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1474 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1475 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001476}
1477
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001478void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001479 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1480 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001481}
1482
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001483void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1484 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001485 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001486 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001487}
1488
Brian Carlstromaded5f72011-10-07 17:15:04 -07001489bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001490 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001491 for (size_t i = 0; i != dex_files_.size(); ++i) {
1492 if (dex_files_[i] == &dex_file) {
1493 return true;
1494 }
1495 }
1496 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001497}
1498
Brian Carlstromaded5f72011-10-07 17:15:04 -07001499bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001500 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001501 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001502}
1503
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001504void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001505 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001506 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001507 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001508 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001509 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001510}
1511
Brian Carlstromaded5f72011-10-07 17:15:04 -07001512void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001513 {
1514 MutexLock mu(dex_lock_);
1515 if (IsDexFileRegisteredLocked(dex_file)) {
1516 return;
1517 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001518 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001519 // Don't alloc while holding the lock, since allocation may need to
1520 // suspend all threads and another thread may need the dex_lock_ to
1521 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001522 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001523 {
1524 MutexLock mu(dex_lock_);
1525 if (IsDexFileRegisteredLocked(dex_file)) {
1526 return;
1527 }
1528 RegisterDexFileLocked(dex_file, dex_cache);
1529 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001530}
1531
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001532void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001533 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001534 RegisterDexFileLocked(dex_file, dex_cache);
1535}
1536
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001537const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001538 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001539 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001540 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1541 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001542 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001543 }
1544 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001545 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001546 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001547}
1548
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001549DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001550 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001551 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001552 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001553 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001554 }
1555 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001556 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001557 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001558}
1559
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001560Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1561 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001562 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001563 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001564 CHECK(primitive_class != NULL);
1565 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001566 primitive_class->SetPrimitiveType(type);
1567 primitive_class->SetStatus(Class::kStatusInitialized);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001568 Class* existing = InsertClass(descriptor, primitive_class, false);
1569 CHECK(existing == NULL) << "InitPrimitiveClass(" << descriptor << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001570 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001571}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001572
Brian Carlstrombe977852011-07-19 14:54:54 -07001573// Create an array class (i.e. the class object for the array, not the
1574// array itself). "descriptor" looks like "[C" or "[[[[B" or
1575// "[Ljava/lang/String;".
1576//
1577// If "descriptor" refers to an array of primitives, look up the
1578// primitive type's internally-generated class object.
1579//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001580// "class_loader" is the class loader of the class that's referring to
1581// us. It's used to ensure that we're looking for the element type in
1582// the right context. It does NOT become the class loader for the
1583// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001584//
1585// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001586Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001587 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001588
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001589 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001590 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001591 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001592 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001593 return NULL;
1594 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001595
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001596 // See if the component type is already loaded. Array classes are
1597 // always associated with the class loader of their underlying
1598 // element type -- an array of Strings goes with the loader for
1599 // java/lang/String -- so we need to look for it there. (The
1600 // caller should have checked for the existence of the class
1601 // before calling here, but they did so with *their* class loader,
1602 // not the component type's loader.)
1603 //
1604 // If we find it, the caller adds "loader" to the class' initiating
1605 // loader list, which should prevent us from going through this again.
1606 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001607 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001608 // are the same, because our caller (FindClass) just did the
1609 // lookup. (Even if we get this wrong we still have correct behavior,
1610 // because we effectively do this lookup again when we add the new
1611 // class to the hash table --- necessary because of possible races with
1612 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001613 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001614 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001615 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001616 return new_class;
1617 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001618 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001619
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001620 // Fill out the fields in the Class.
1621 //
1622 // It is possible to execute some methods against arrays, because
1623 // all arrays are subclasses of java_lang_Object_, so we need to set
1624 // up a vtable. We can just point at the one in java_lang_Object_.
1625 //
1626 // Array classes are simple enough that we don't need to do a full
1627 // link step.
1628
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001629 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001630 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001631 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001632 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001633 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001634 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001635 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001636 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001637 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001638 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001639 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001640 }
1641 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001642 if (new_class.get() == NULL) {
1643 new_class.reset(AllocClass(sizeof(Class)));
1644 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001645 return NULL;
1646 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001647 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001648 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001649 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001650 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001651 new_class->SetSuperClass(java_lang_Object);
1652 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001653 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001654 new_class->SetClassLoader(component_type->GetClassLoader());
1655 new_class->SetStatus(Class::kStatusInitialized);
1656 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001657 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001658
1659
1660 // All arrays have java/lang/Cloneable and java/io/Serializable as
1661 // interfaces. We need to set that up here, so that stuff like
1662 // "instanceof" works right.
1663 //
1664 // Note: The GC could run during the call to FindSystemClass,
1665 // so we need to make sure the class object is GC-valid while we're in
1666 // there. Do this by clearing the interface list so the GC will just
1667 // think that the entries are null.
1668
1669
1670 // Use the single, global copies of "interfaces" and "iftable"
1671 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001672 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001673 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001674
1675 // Inherit access flags from the component type. Arrays can't be
1676 // used as a superclass or interface, so we want to add "final"
1677 // and remove "interface".
1678 //
1679 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001680 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001681 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001682 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1683 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001684
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001685 Class* existing = InsertClass(descriptor, new_class.get(), false);
1686 if (existing == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001687 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001688 }
1689 // Another thread must have loaded the class after we
1690 // started but before we finished. Abandon what we've
1691 // done.
1692 //
1693 // (Yes, this happens.)
1694
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001695 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001696}
1697
1698Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001699 switch (Primitive::GetType(type)) {
1700 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001701 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001702 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001703 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001704 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001705 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001706 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001707 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001708 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001709 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001710 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001711 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001712 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001713 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001714 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001715 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001716 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001717 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001718 case Primitive::kPrimNot:
1719 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001720 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001721 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001722 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001723 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001724}
1725
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001726Class* ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001727 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001728 DexCache* dex_cache = klass->GetDexCache();
1729 std::string source;
1730 if (dex_cache != NULL) {
1731 source += " from ";
1732 source += dex_cache->GetLocation()->ToModifiedUtf8();
1733 }
1734 LOG(INFO) << "Loaded class " << descriptor << source;
1735 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001736 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001737 MutexLock mu(classes_lock_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001738 Table& classes = image_class ? image_classes_ : classes_;
1739 Class* existing = LookupClass(descriptor.data(), klass->GetClassLoader(), hash, classes);
1740#ifndef NDEBUG
1741 // Check we don't have the class in the other table in error
1742 Table& other_classes = image_class ? classes_ : image_classes_;
1743 CHECK(LookupClass(descriptor.data(), klass->GetClassLoader(), hash, other_classes) == NULL);
1744#endif
1745 if (existing != NULL) {
1746 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07001747 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001748 classes.insert(std::make_pair(hash, klass));
1749 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001750}
1751
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001752bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1753 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001754 MutexLock mu(classes_lock_);
Elliott Hughese5448b52012-01-18 16:44:06 -08001755 typedef Table::iterator It; // TODO: C++0x auto
Brian Carlstromae826982011-11-09 01:33:42 -08001756 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001757 ClassHelper kh;
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001758 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001759 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001760 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001761 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001762 classes_.erase(it);
1763 return true;
1764 }
1765 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001766 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001767 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001768 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001769 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001770 image_classes_.erase(it);
1771 return true;
1772 }
1773 }
1774 return false;
1775}
1776
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001777Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1778 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001779 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001780 // TODO: determine if its better to search classes_ or image_classes_ first
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001781 Class* klass = LookupClass(descriptor, class_loader, hash, classes_);
1782 if (klass != NULL) {
1783 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001784 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001785 return LookupClass(descriptor, class_loader, hash, image_classes_);
1786}
1787
1788Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader,
1789 size_t hash, const Table& classes) {
1790 ClassHelper kh(NULL, this);
1791 typedef Table::const_iterator It; // TODO: C++0x auto
1792 for (It it = classes.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001793 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001794 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001795 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001796#ifndef NDEBUG
1797 for (++it; it != end && it->first == hash; ++it) {
1798 kh.ChangeClass(it->second);
1799 CHECK(!(strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader))
1800 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
1801 << PrettyClass(it->second) << " " << it->second << " " << it->second->GetClassLoader();
1802 }
1803#endif
Ian Rogers5d76c432011-10-31 21:42:49 -07001804 return klass;
1805 }
1806 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001807 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001808}
1809
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001810void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001811 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001812 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001813 MutexLock mu(classes_lock_);
1814 typedef Table::const_iterator It; // TODO: C++0x auto
1815 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001816 ClassHelper kh(NULL, this);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001817 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001818 Class* klass = it->second;
1819 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001820 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001821 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001822 }
1823 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001824 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001825 Class* klass = it->second;
1826 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001827 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001828 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001829 }
1830 }
1831}
1832
Ian Rogersc20a83e2012-01-18 18:15:32 -08001833#ifndef NDEBUG
1834static void CheckMethodsHaveGcMaps(Class* klass) {
1835 if (!Runtime::Current()->IsStarted()) {
1836 return;
1837 }
1838 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
1839 Method* method = klass->GetDirectMethod(i);
1840 if (!method->IsNative() && !method->IsAbstract()) {
1841 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1842 }
1843 }
1844 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
1845 Method* method = klass->GetVirtualMethod(i);
1846 if (!method->IsNative() && !method->IsAbstract()) {
1847 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1848 }
1849 }
1850}
1851#else
1852static void CheckMethodsHaveGcMaps(Class* klass) {
1853}
1854#endif
1855
jeffhao98eacac2011-09-14 16:11:53 -07001856void ClassLinker::VerifyClass(Class* klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001857 // TODO: assert that the monitor on the Class is held
jeffhao98eacac2011-09-14 16:11:53 -07001858 if (klass->IsVerified()) {
1859 return;
1860 }
1861
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001862 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved) << PrettyClass(klass);
jeffhao98eacac2011-09-14 16:11:53 -07001863 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001864
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001865 // Try to use verification information from oat file, otherwise do runtime verification
1866 const DexFile& dex_file = FindDexFile(klass->GetDexCache());
1867 if (VerifyClassUsingOatFile(dex_file, klass) || verifier::DexVerifier::VerifyClass(klass)) {
1868 // Make sure all classes referenced by catch blocks are resolved
1869 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001870 klass->SetStatus(Class::kStatusVerified);
Ian Rogersc20a83e2012-01-18 18:15:32 -08001871 // Sanity check that a verified class has GC maps on all methods
1872 CheckMethodsHaveGcMaps(klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001873 } else {
1874 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001875 Thread* self = Thread::Current();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001876 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException()) << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001877 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001878 PrettyDescriptor(klass).c_str());
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001879 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001880 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001881 }
jeffhao98eacac2011-09-14 16:11:53 -07001882}
1883
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001884bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, Class* klass) {
1885 if (!Runtime::Current()->IsStarted()) {
1886 return false;
1887 }
1888 if (ClassLoader::UseCompileTimeClassPath()) {
1889 return false;
1890 }
1891 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
1892 if (oat_file == NULL) {
1893 return false;
1894 }
1895 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1896 CHECK(oat_dex_file != NULL) << PrettyClass(klass);
1897 const char* descriptor = ClassHelper(klass).GetDescriptor();
1898 uint32_t class_def_index;
1899 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1900 CHECK(found) << descriptor;
1901 UniquePtr<const OatFile::OatClass> oat_class(oat_dex_file->GetOatClass(class_def_index));
1902 CHECK(oat_class.get() != NULL) << descriptor;
1903 Class::Status status = oat_class->GetStatus();
1904 if (status == Class::kStatusError) {
1905 ThrowEarlierClassFailure(klass);
1906 klass->SetVerifyErrorClass(Thread::Current()->GetException()->GetClass());
1907 klass->SetStatus(Class::kStatusError);
1908 return true;
1909 }
1910 if (status == Class::kStatusVerified || status == Class::kStatusInitialized) {
1911 return true;
1912 }
1913 if (status == Class::kStatusNotReady) {
1914 return false;
1915 }
1916 LOG(FATAL) << "Unexpected class status: " << status;
1917 return false;
1918}
1919
1920void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, Class* klass) {
1921 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
1922 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
1923 }
1924 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
1925 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
1926 }
1927}
1928
1929void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, Method* method) {
1930 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
1931 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
1932 if (code_item == NULL) {
1933 return; // native or abstract method
1934 }
1935 if (code_item->tries_size_ == 0) {
1936 return; // nothing to process
1937 }
1938 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
1939 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
1940 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1941 for (uint32_t idx = 0; idx < handlers_size; idx++) {
1942 CatchHandlerIterator iterator(handlers_ptr);
1943 for (; iterator.HasNext(); iterator.Next()) {
1944 // Ensure exception types are resolved so that they don't need resolution to be delivered,
1945 // unresolved exception types will be ignored by exception delivery
1946 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
1947 Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
1948 if (exception_type == NULL) {
1949 DCHECK(Thread::Current()->IsExceptionPending());
1950 Thread::Current()->ClearException();
1951 }
1952 }
1953 }
1954 handlers_ptr = iterator.EndDataPointer();
1955 }
1956}
1957
Ian Rogersc2b44472011-12-14 21:17:17 -08001958static void CheckProxyConstructor(Method* constructor);
1959static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
1960
Jesse Wilson95caa792011-10-12 18:14:17 -04001961Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001962 ClassLoader* loader, ObjectArray<Method>* methods,
1963 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08001964 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001965 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08001966 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001967 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001968 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001969 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001970 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001971 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07001972 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001973 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08001974
1975 klass->SetStatus(Class::kStatusIdx);
1976
1977 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
1978
1979 // Create static field that holds throws, instance fields are inherited
1980 klass->SetSFields(AllocObjectArray<Field>(1));
1981 SirtRef<Field> sfield(AllocField());
1982 klass->SetStaticField(0, sfield.get());
1983 sfield->SetDexFieldIndex(-1);
1984 sfield->SetDeclaringClass(klass.get());
1985 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001986
Ian Rogers466bb252011-10-14 03:29:56 -07001987 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001988 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001989 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04001990
Ian Rogers466bb252011-10-14 03:29:56 -07001991 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001992 size_t num_virtual_methods = methods->GetLength();
1993 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1994 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001995 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001996 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04001997 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001998
1999 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
2000 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
2001 DCHECK(!Thread::Current()->IsExceptionPending());
2002
2003 // Link the fields and virtual methods, creating vtable and iftables
2004 if (!LinkClass(klass, interfaces)) {
Jesse Wilson95caa792011-10-12 18:14:17 -04002005 DCHECK(Thread::Current()->IsExceptionPending());
2006 return NULL;
2007 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002008 sfield->SetObject(NULL, throws); // initialize throws field
2009 klass->SetStatus(Class::kStatusInitialized);
2010
2011 // sanity checks
2012#ifndef NDEBUG
2013 bool debug = true;
2014#else
2015 bool debug = false;
2016#endif
2017 if (debug) {
2018 CHECK(klass->GetIFields() == NULL);
2019 CheckProxyConstructor(klass->GetDirectMethod(0));
2020 for (size_t i = 0; i < num_virtual_methods; ++i) {
2021 SirtRef<Method> prototype(methods->Get(i));
2022 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
2023 }
Brian Carlstrom89521892011-12-07 22:05:07 -08002024 std::string throws_field_name("java.lang.Class[][] ");
Ian Rogersc2b44472011-12-14 21:17:17 -08002025 throws_field_name += name->ToModifiedUtf8();
2026 throws_field_name += ".throws";
2027 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
2028
2029 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
2030 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
2031 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002032 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04002033}
2034
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002035std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
2036 DCHECK(proxy_class->IsProxyClass());
2037 String* name = proxy_class->GetName();
2038 DCHECK(name != NULL);
2039 return DotToDescriptor(name->ToModifiedUtf8().c_str());
2040}
2041
2042
2043Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07002044 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07002045 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04002046 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07002047 Method* proxy_constructor = proxy_direct_methods->Get(2);
2048 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
2049 // code_ too)
2050 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
2051 // Make this constructor public and fix the class to be our Proxy version
2052 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002053 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08002054 return constructor;
2055}
2056
2057static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07002058 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002059 MethodHelper mh(constructor);
2060 CHECK_STREQ(mh.GetName(), "<init>");
Elliott Hughesba8eee12012-01-24 20:25:24 -08002061 CHECK_EQ(mh.GetSignature(), std::string("(Ljava/lang/reflect/InvocationHandler;)V"));
Ian Rogers466bb252011-10-14 03:29:56 -07002062 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04002063}
2064
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002065Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
2066 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
2067 // prototype method
2068 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
2069 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07002070 // as necessary
2071 Method* method = down_cast<Method*>(prototype->Clone());
2072
2073 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
2074 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002075 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07002076 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002077
Ian Rogers466bb252011-10-14 03:29:56 -07002078 // At runtime the method looks like a reference and argument saving method, clone the code
2079 // related parameters from this method.
2080 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
2081 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
2082 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
2083 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
2084 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08002085 return method;
2086}
Jesse Wilson95caa792011-10-12 18:14:17 -04002087
Ian Rogersc2b44472011-12-14 21:17:17 -08002088static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07002089 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002090 CHECK(!prototype->IsFinal());
2091 CHECK(method->IsFinal());
2092 CHECK(!method->IsAbstract());
2093 MethodHelper mh(method);
2094 const char* method_name = mh.GetName();
2095 const char* method_shorty = mh.GetShorty();
2096 Class* method_return = mh.GetReturnType();
2097
2098 mh.ChangeMethod(prototype.get());
2099
2100 CHECK_STREQ(mh.GetName(), method_name);
2101 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07002102
2103 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002104 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04002105}
2106
Brian Carlstrom25c33252011-09-18 15:58:35 -07002107bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002108 CHECK(klass->IsResolved() || klass->IsErroneous())
2109 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002110
Carl Shapirob5573532011-07-12 18:22:59 -07002111 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002112
Brian Carlstrom25c33252011-09-18 15:58:35 -07002113 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002114 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002115 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002116 ObjectLock lock(klass);
2117
Brian Carlstromd1422f82011-09-28 11:37:09 -07002118 if (klass->GetStatus() == Class::kStatusInitialized) {
2119 return true;
2120 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002121
Brian Carlstromd1422f82011-09-28 11:37:09 -07002122 if (klass->IsErroneous()) {
2123 ThrowEarlierClassFailure(klass);
2124 return false;
2125 }
2126
2127 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07002128 VerifyClass(klass);
2129 if (klass->GetStatus() != Class::kStatusVerified) {
Ian Rogers595799e2012-01-11 17:32:51 -08002130 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002131 return false;
2132 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002133 }
2134
Brian Carlstrom25c33252011-09-18 15:58:35 -07002135 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
2136 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002137 // if the class has a <clinit> but we can't run it during compilation,
Ian Rogers595799e2012-01-11 17:32:51 -08002138 // don't bother going to kStatusInitializing. We return true to maintain
2139 // the invariant that a false result implies there is a pending exception.
2140 return true;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002141 }
2142
Brian Carlstromd1422f82011-09-28 11:37:09 -07002143 // If the class is kStatusInitializing, either this thread is
2144 // initializing higher up the stack or another thread has beat us
2145 // to initializing and we need to wait. Either way, this
2146 // invocation of InitializeClass will not be responsible for
2147 // running <clinit> and will return.
2148 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002149 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002150 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002151 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002152 return true;
2153 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002154 // No. That's fine. Wait for another thread to finish initializing.
2155 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002156 }
2157
2158 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers595799e2012-01-11 17:32:51 -08002159 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002160 klass->SetStatus(Class::kStatusError);
2161 return false;
2162 }
2163
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002164 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified) << PrettyClass(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002165
Elliott Hughesdcc24742011-09-07 14:02:44 -07002166 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002167 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002168 }
2169
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002170 uint64_t t0 = NanoTime();
2171
Brian Carlstrom25c33252011-09-18 15:58:35 -07002172 if (!InitializeSuperClass(klass, can_run_clinit)) {
Ian Rogers595799e2012-01-11 17:32:51 -08002173 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002174 return false;
2175 }
2176
2177 InitializeStaticFields(klass);
2178
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002179 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002180 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002181 }
2182
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002183 uint64_t t1 = NanoTime();
2184
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002185 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002186 {
2187 ObjectLock lock(klass);
2188
2189 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002190 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002191 klass->SetStatus(Class::kStatusError);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002192 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002193 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002194 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2195 RuntimeStats* thread_stats = self->GetStats();
2196 ++global_stats->class_init_count;
2197 ++thread_stats->class_init_count;
2198 global_stats->class_init_time_ns += (t1 - t0);
2199 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002200 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002201 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002202 ClassHelper kh(klass);
2203 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002204 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002205 }
2206 lock.NotifyAll();
2207 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002208 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002209}
2210
Brian Carlstromd1422f82011-09-28 11:37:09 -07002211bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
2212 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002213 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002214 lock.Wait();
2215
2216 // When we wake up, repeat the test for init-in-progress. If
2217 // there's an exception pending (only possible if
2218 // "interruptShouldThrow" was set), bail out.
2219 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002220 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002221 klass->SetStatus(Class::kStatusError);
2222 return false;
2223 }
2224 // Spurious wakeup? Go back to waiting.
2225 if (klass->GetStatus() == Class::kStatusInitializing) {
2226 continue;
2227 }
2228 if (klass->IsErroneous()) {
2229 // The caller wants an exception, but it was thrown in a
2230 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002231 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002232 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002233 return false;
2234 }
2235 if (klass->IsInitialized()) {
2236 return true;
2237 }
2238 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2239 }
2240 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2241}
2242
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002243bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2244 if (klass->IsInterface()) {
2245 return true;
2246 }
2247 // begin with the methods local to the superclass
2248 if (klass->HasSuperClass() &&
2249 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2250 const Class* super = klass->GetSuperClass();
Ian Rogers595799e2012-01-11 17:32:51 -08002251 for (int i = super->GetVTable()->GetLength() - 1; i >= 0; --i) {
2252 const Method* method = klass->GetVTable()->Get(i);
2253 if (method != super->GetVTable()->Get(i) &&
2254 !IsSameMethodSignatureInDifferentClassContexts(method, super, klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002255 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2256 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2257 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002258 return false;
2259 }
2260 }
2261 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002262 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2263 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2264 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002265 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2266 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002267 const Method* method = interface_entry->GetMethodArray()->Get(j);
Ian Rogers595799e2012-01-11 17:32:51 -08002268 if (!IsSameMethodSignatureInDifferentClassContexts(method, interface,
2269 method->GetDeclaringClass())) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002270 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2271 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2272 PrettyMethod(method).c_str(),
2273 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002274 return false;
2275 }
2276 }
2277 }
2278 }
2279 return true;
2280}
2281
Ian Rogers595799e2012-01-11 17:32:51 -08002282// Returns true if classes referenced by the signature of the method are the
2283// same classes in klass1 as they are in klass2.
2284bool ClassLinker::IsSameMethodSignatureInDifferentClassContexts(const Method* method,
2285 const Class* klass1,
2286 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002287 if (klass1 == klass2) {
2288 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002289 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002290 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002291 const DexFile::ProtoId& proto_id =
2292 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002293 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2294 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002295 if (descriptor == NULL) {
2296 break;
2297 }
2298 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2299 // Found a non-primitive type.
Ian Rogers595799e2012-01-11 17:32:51 -08002300 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002301 return false;
2302 }
2303 }
2304 }
2305 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002306 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002307 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Ian Rogers595799e2012-01-11 17:32:51 -08002308 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002309 return false;
2310 }
2311 }
2312 return true;
2313}
2314
Ian Rogers595799e2012-01-11 17:32:51 -08002315// Returns true if the descriptor resolves to the same class in the context of klass1 and klass2.
2316bool ClassLinker::IsSameDescriptorInDifferentClassContexts(const char* descriptor,
2317 const Class* klass1,
2318 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002319 CHECK(descriptor != NULL);
2320 CHECK(klass1 != NULL);
2321 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002322 if (klass1 == klass2) {
2323 return true;
2324 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002325 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Ian Rogers595799e2012-01-11 17:32:51 -08002326 if (found1 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002327 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002328 }
Ian Rogers595799e2012-01-11 17:32:51 -08002329 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
2330 if (found2 == NULL) {
2331 Thread::Current()->ClearException();
2332 }
2333 return found1 == found2;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002334}
2335
Brian Carlstrom25c33252011-09-18 15:58:35 -07002336bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002337 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002338 if (!klass->IsInterface() && klass->HasSuperClass()) {
2339 Class* super_class = klass->GetSuperClass();
2340 if (super_class->GetStatus() != Class::kStatusInitialized) {
2341 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002342 Thread* self = Thread::Current();
2343 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002344 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002345 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002346 // TODO: check for a pending exception
2347 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002348 if (!can_run_clinit) {
2349 // Don't set status to error when we can't run <clinit>.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002350 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing) << PrettyClass(klass);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002351 klass->SetStatus(Class::kStatusVerified);
2352 return false;
2353 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002354 klass->SetStatus(Class::kStatusError);
2355 klass->NotifyAll();
2356 return false;
2357 }
2358 }
2359 }
2360 return true;
2361}
2362
Brian Carlstrom25c33252011-09-18 15:58:35 -07002363bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002364 CHECK(c != NULL);
2365 if (c->IsInitialized()) {
2366 return true;
2367 }
2368
Elliott Hughes5f791332011-09-15 17:45:30 -07002369 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002370 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Ian Rogers595799e2012-01-11 17:32:51 -08002371 bool success = InitializeClass(c, can_run_clinit);
2372 if (!success) {
2373 CHECK(self->IsExceptionPending());
2374 }
2375 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002376}
2377
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002378void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002379 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002380 const ClassLoader* cl = c->GetClassLoader();
2381 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002382 ClassDataItemIterator it(dex_file, class_data);
2383 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2384 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002385 }
2386}
2387
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002388void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002389 size_t num_static_fields = klass->NumStaticFields();
2390 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002391 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002392 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002393 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002394 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002395 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002396 return;
2397 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002398 ClassHelper kh(klass);
2399 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002400 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002401 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002402 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002403
Ian Rogers0571d352011-11-03 19:51:38 -07002404 if (it.HasNext()) {
2405 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2406 std::map<uint32_t, Field*> field_map;
2407 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2408 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2409 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002410 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002411 }
2412}
2413
Ian Rogersc2b44472011-12-14 21:17:17 -08002414bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002415 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002416 if (!LinkSuperClass(klass)) {
2417 return false;
2418 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002419 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002420 return false;
2421 }
2422 if (!LinkInstanceFields(klass)) {
2423 return false;
2424 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002425 if (!LinkStaticFields(klass)) {
2426 return false;
2427 }
2428 CreateReferenceInstanceOffsets(klass);
2429 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002430 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2431 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002432 return true;
2433}
2434
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002435bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002436 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002437 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2438 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
Ian Rogerscab01012012-01-10 17:35:46 -08002439 CHECK(class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002440 uint16_t super_class_idx = class_def->superclass_idx_;
2441 if (super_class_idx != DexFile::kDexNoIndex16) {
2442 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002443 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002444 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002445 return false;
2446 }
Ian Rogersbe125a92012-01-11 15:19:49 -08002447 // Verify
2448 if (!klass->CanAccess(super_class)) {
2449 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2450 "Class %s extended by class %s is inaccessible",
2451 PrettyDescriptor(super_class).c_str(),
2452 PrettyDescriptor(klass.get()).c_str());
2453 return false;
2454 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002455 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002456 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002457 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2458 if (interfaces != NULL) {
2459 for (size_t i = 0; i < interfaces->Size(); i++) {
2460 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2461 Class* interface = ResolveType(dex_file, idx, klass.get());
2462 if (interface == NULL) {
2463 DCHECK(Thread::Current()->IsExceptionPending());
2464 return false;
2465 }
2466 // Verify
2467 if (!klass->CanAccess(interface)) {
2468 // TODO: the RI seemed to ignore this in my testing.
2469 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2470 "Interface %s implemented by class %s is inaccessible",
2471 PrettyDescriptor(interface).c_str(),
2472 PrettyDescriptor(klass.get()).c_str());
2473 return false;
2474 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002475 }
2476 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002477 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002478 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002479 return true;
2480}
2481
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002482bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002483 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002484 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002485 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002486 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002487 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002488 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002489 return false;
2490 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002491 return true;
2492 }
2493 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002494 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002495 return false;
2496 }
2497 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002498 if (super->IsFinal() || super->IsInterface()) {
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002499 Thread* thread = Thread::Current();
2500 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002501 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002502 PrettyDescriptor(super).c_str(),
2503 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002504 super->IsFinal() ? "declared final" : "an interface");
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002505 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002506 return false;
2507 }
2508 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002509 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002510 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002511 PrettyDescriptor(super).c_str(),
2512 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002513 return false;
2514 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002515
2516 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2517 if (super->IsFinalizable()) {
2518 klass->SetFinalizable();
2519 }
2520
Elliott Hughes2da50362011-10-10 16:57:08 -07002521 // Inherit reference flags (if any) from the superclass.
2522 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2523 if (reference_flags != 0) {
2524 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2525 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002526 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002527 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002528 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002529 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002530 return false;
2531 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002532
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002533#ifndef NDEBUG
2534 // Ensure super classes are fully resolved prior to resolving fields..
2535 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002536 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002537 super = super->GetSuperClass();
2538 }
2539#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002540 return true;
2541}
2542
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002543// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002544bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002545 if (klass->IsInterface()) {
2546 // No vtable.
2547 size_t count = klass->NumVirtualMethods();
2548 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002549 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002550 return false;
2551 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002552 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002553 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002554 }
jeffhaobdb76512011-09-07 11:43:16 -07002555 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002556 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002557 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002558 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002559 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002560 }
2561 return true;
2562}
2563
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002564bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002565 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002566 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2567 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002568 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002569 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002570 SirtRef<ObjectArray<Method> > vtable(klass->GetSuperClass()->GetVTable()->CopyOf(max_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002571 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002572 MethodHelper local_mh(NULL, this);
2573 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002574 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002575 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002576 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002577 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002578 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002579 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002580 super_mh.ChangeMethod(super_method);
2581 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002582 // Verify
2583 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002584 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002585 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002586 PrettyDescriptor(klass.get()).c_str(),
2587 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002588 return false;
2589 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002590 vtable->Set(j, local_method);
2591 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002592 break;
2593 }
2594 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002595 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002596 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002597 vtable->Set(actual_count, local_method);
2598 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002599 actual_count += 1;
2600 }
2601 }
2602 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002603 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002604 return false;
2605 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002606 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002607 CHECK_LE(actual_count, max_count);
2608 if (actual_count < max_count) {
Ian Rogers30fab402012-01-23 15:43:46 -08002609 vtable.reset(vtable->CopyOf(actual_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002610 }
Ian Rogers30fab402012-01-23 15:43:46 -08002611 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002612 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002613 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002614 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002615 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002616 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002617 return false;
2618 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002619 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002620 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002621 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2622 vtable->Set(i, virtual_method);
2623 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002624 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002625 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002626 }
2627 return true;
2628}
2629
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002630bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002631 size_t super_ifcount;
2632 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002633 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002634 } else {
2635 super_ifcount = 0;
2636 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002637 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002638 ClassHelper kh(klass.get(), this);
2639 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2640 ifcount += num_interfaces;
2641 for (size_t i = 0; i < num_interfaces; i++) {
2642 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2643 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002644 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002645 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002646 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002647 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002648 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002649 return true;
2650 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002651 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002652 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002653 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2654 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogersb52b01a2012-01-12 17:01:38 -08002655 Class* super_interface = super_iftable->Get(i)->GetInterface();
2656 iftable->Set(i, AllocInterfaceEntry(super_interface));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002657 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002658 }
2659 // Flatten the interface inheritance hierarchy.
2660 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002661 for (size_t i = 0; i < num_interfaces; i++) {
2662 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002663 DCHECK(interface != NULL);
2664 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002665 ClassHelper ih(interface);
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002666 Thread* thread = Thread::Current();
2667 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002668 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002669 PrettyDescriptor(klass.get()).c_str(),
2670 PrettyDescriptor(ih.GetDescriptor()).c_str());
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002671 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002672 return false;
2673 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002674 // Check if interface is already in iftable
2675 bool duplicate = false;
2676 for (size_t j = 0; j < idx; j++) {
2677 Class* existing_interface = iftable->Get(j)->GetInterface();
2678 if (existing_interface == interface) {
2679 duplicate = true;
2680 break;
2681 }
2682 }
2683 if (!duplicate) {
2684 // Add this non-duplicate interface.
2685 iftable->Set(idx++, AllocInterfaceEntry(interface));
2686 // Add this interface's non-duplicate super-interfaces.
2687 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2688 Class* super_interface = interface->GetIfTable()->Get(j)->GetInterface();
2689 bool super_duplicate = false;
2690 for (size_t k = 0; k < idx; k++) {
2691 Class* existing_interface = iftable->Get(k)->GetInterface();
2692 if (existing_interface == super_interface) {
2693 super_duplicate = true;
2694 break;
2695 }
2696 }
2697 if (!super_duplicate) {
2698 iftable->Set(idx++, AllocInterfaceEntry(super_interface));
2699 }
2700 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002701 }
2702 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002703 // Shrink iftable in case duplicates were found
2704 if (idx < ifcount) {
2705 iftable.reset(iftable->CopyOf(idx));
2706 ifcount = idx;
2707 } else {
2708 CHECK_EQ(idx, ifcount);
2709 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002710 klass->SetIfTable(iftable.get());
Elliott Hughes4681c802011-09-25 18:04:37 -07002711
2712 // If we're an interface, we don't need the vtable pointers, so we're done.
2713 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002714 return true;
2715 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002716 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002717 MethodHelper vtable_mh(NULL, this);
2718 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002719 for (size_t i = 0; i < ifcount; ++i) {
2720 InterfaceEntry* interface_entry = iftable->Get(i);
2721 Class* interface = interface_entry->GetInterface();
2722 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2723 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002724 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002725 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2726 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002727 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002728 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002729 // For each method listed in the interface's method list, find the
2730 // matching method in our class's method list. We want to favor the
2731 // subclass over the superclass, which just requires walking
2732 // back from the end of the vtable. (This only matters if the
2733 // superclass defines a private method and this class redefines
2734 // it -- otherwise it would use the same vtable slot. In .dex files
2735 // those don't end up in the virtual method table, so it shouldn't
2736 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002737 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2738 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002739 vtable_mh.ChangeMethod(vtable_method);
2740 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002741 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002742 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002743 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002744 return false;
2745 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002746 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002747 break;
2748 }
2749 }
2750 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002751 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002752 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002753 Method* mir_method = miranda_list[mir];
2754 vtable_mh.ChangeMethod(mir_method);
2755 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002756 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002757 break;
2758 }
2759 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002760 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002761 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002762 miranda_method.reset(AllocMethod());
2763 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2764 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002765 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002766 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002767 }
2768 }
2769 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002770 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002771 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002772 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002773 klass->SetVirtualMethods((old_method_count == 0)
2774 ? AllocObjectArray<Method>(new_method_count)
2775 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002776
Ian Rogers30fab402012-01-23 15:43:46 -08002777 SirtRef<ObjectArray<Method> > vtable(klass->GetVTableDuringLinking());
2778 CHECK(vtable.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002779 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002780 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers30fab402012-01-23 15:43:46 -08002781 vtable.reset(vtable->CopyOf(new_vtable_count));
Elliott Hughes4681c802011-09-25 18:04:37 -07002782 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002783 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002784 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002785 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2786 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2787 klass->SetVirtualMethod(old_method_count + i, method);
2788 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002789 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002790 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002791 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002792 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002793
2794 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2795 for (int i = 0; i < vtable->GetLength(); ++i) {
2796 CHECK(vtable->Get(i) != NULL);
2797 }
2798
2799// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2800
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002801 return true;
2802}
2803
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002804bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2805 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002806 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002807}
2808
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002809bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2810 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002811 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002812 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002813 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002814 return success;
2815}
2816
Brian Carlstromdbc05252011-09-09 01:59:59 -07002817struct LinkFieldsComparator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002818 explicit LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002819 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002820 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002821 fh_->ChangeField(field1);
2822 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2823 fh_->ChangeField(field2);
2824 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002825 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2826 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2827 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2828 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002829 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2830 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2831 if (order1 != order2) {
2832 return order1 < order2;
2833 }
2834
2835 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002836 fh_->ChangeField(field1);
2837 StringPiece name1(fh_->GetName());
2838 fh_->ChangeField(field2);
2839 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002840 return name1 < name2;
2841 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002842
2843 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002844};
2845
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002846bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002847 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002848 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002849
2850 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002851 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002852
2853 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002854 size_t size;
2855 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002856 if (is_static) {
2857 size = klass->GetClassSize();
2858 field_offset = Class::FieldsOffset();
2859 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002860 Class* super_class = klass->GetSuperClass();
2861 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002862 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002863 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002864 }
2865 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002866 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002867
Brian Carlstromdbc05252011-09-09 01:59:59 -07002868 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002869
Brian Carlstromdbc05252011-09-09 01:59:59 -07002870 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002871 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002872 std::deque<Field*> grouped_and_sorted_fields;
2873 for (size_t i = 0; i < num_fields; i++) {
2874 grouped_and_sorted_fields.push_back(fields->Get(i));
2875 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002876 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002877 std::sort(grouped_and_sorted_fields.begin(),
2878 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002879 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002880
2881 // References should be at the front.
2882 size_t current_field = 0;
2883 size_t num_reference_fields = 0;
2884 for (; current_field < num_fields; current_field++) {
2885 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002886 fh.ChangeField(field);
2887 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002888 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002889 if (isPrimitive) {
2890 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002891 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002892 grouped_and_sorted_fields.pop_front();
2893 num_reference_fields++;
2894 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002895 field->SetOffset(field_offset);
2896 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002897 }
2898
2899 // Now we want to pack all of the double-wide fields together. If
2900 // we're not aligned, though, we want to shuffle one 32-bit field
2901 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002902 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002903 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2904 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002905 fh.ChangeField(field);
2906 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002907 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2908 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002909 continue;
2910 }
2911 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002912 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002913 // drop the consumed field
2914 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2915 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002916 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002917 // whether we found a 32-bit field for padding or not, we advance
2918 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002919 }
2920
2921 // Alignment is good, shuffle any double-wide fields forward, and
2922 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002923 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002924 while (!grouped_and_sorted_fields.empty()) {
2925 Field* field = grouped_and_sorted_fields.front();
2926 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002927 fh.ChangeField(field);
2928 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002929 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002930 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002931 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002932 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002933 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002934 ? sizeof(uint64_t)
2935 : sizeof(uint32_t)));
2936 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002937 }
2938
Elliott Hughesadb460d2011-10-05 17:02:34 -07002939 // 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 -08002940 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
2941 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002942 // We know there are no non-reference fields in the Reference classes, and we know
2943 // that 'referent' is alphabetically last, so this is easy...
2944 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002945 fh.ChangeField(fields->Get(num_fields - 1));
Elliott Hughesba8eee12012-01-24 20:25:24 -08002946 CHECK_STREQ(fh.GetName(), "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07002947 --num_reference_fields;
2948 }
2949
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002950#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002951 // Make sure that all reference fields appear before
2952 // non-reference fields, and all double-wide fields are aligned.
2953 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002954 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002955 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002956 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002957 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002958 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002959 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002960 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2961 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002962 fh.ChangeField(field);
2963 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002964 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002965 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002966 is_primitive = true; // We lied above, so we have to expect a lie here.
2967 }
2968 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002969 if (!seen_non_ref) {
2970 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002971 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002972 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002973 } else {
2974 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002975 }
2976 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002977 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002978 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002979 }
2980#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002981 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002982 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002983 if (is_static) {
2984 klass->SetNumReferenceStaticFields(num_reference_fields);
2985 klass->SetClassSize(size);
2986 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002987 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002988 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002989 klass->SetObjectSize(size);
2990 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002991 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002992 return true;
2993}
2994
2995// Set the bitmap of reference offsets, refOffsets, from the ifields
2996// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002997void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002998 uint32_t reference_offsets = 0;
2999 Class* super_class = klass->GetSuperClass();
3000 if (super_class != NULL) {
3001 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003002 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003003 if (reference_offsets == CLASS_WALK_SUPER) {
3004 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003005 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003006 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003007 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003008 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003009}
3010
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003011void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003012 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003013}
3014
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003015void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003016 uint32_t reference_offsets) {
3017 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003018 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
3019 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003020 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003021 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003022 // All of the fields that contain object references are guaranteed
3023 // to be at the beginning of the fields list.
3024 for (size_t i = 0; i < num_reference_fields; ++i) {
3025 // Note that byte_offset is the offset from the beginning of
3026 // object, not the offset into instance data
3027 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003028 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003029 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
3030 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
3031 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07003032 CHECK_NE(new_bit, 0U);
3033 reference_offsets |= new_bit;
3034 } else {
3035 reference_offsets = CLASS_WALK_SUPER;
3036 break;
3037 }
3038 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003039 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003040 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003041 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003042 } else {
3043 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003044 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003045}
3046
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003047String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07003048 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003049 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003050 if (resolved != NULL) {
3051 return resolved;
3052 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003053 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
3054 int32_t utf16_length = dex_file.GetStringLength(string_id);
3055 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07003056 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003057 dex_cache->SetResolvedString(string_idx, string);
3058 return string;
3059}
3060
3061Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003062 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003063 DexCache* dex_cache,
3064 const ClassLoader* class_loader) {
3065 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003066 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07003067 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003068 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003069 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05003070 // TODO: we used to throw here if resolved's class loader was not the
3071 // boot class loader. This was to permit different classes with the
3072 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003073 dex_cache->SetResolvedType(type_idx, resolved);
3074 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08003075 CHECK(Thread::Current()->IsExceptionPending())
3076 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003077 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003078 }
3079 return resolved;
3080}
3081
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003082Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
3083 uint32_t method_idx,
3084 DexCache* dex_cache,
3085 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003086 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003087 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
3088 if (resolved != NULL) {
3089 return resolved;
3090 }
3091 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3092 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
3093 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07003094 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003095 return NULL;
3096 }
3097
Ian Rogers0571d352011-11-03 19:51:38 -07003098 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
3099 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003100 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003101 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003102 } else if (klass->IsInterface()) {
3103 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003104 } else {
3105 resolved = klass->FindVirtualMethod(name, signature);
3106 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003107 if (resolved != NULL) {
3108 dex_cache->SetResolvedMethod(method_idx, resolved);
3109 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003110 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003111 }
3112 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003113}
3114
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003115Field* ClassLinker::ResolveField(const DexFile& dex_file,
3116 uint32_t field_idx,
3117 DexCache* dex_cache,
3118 const ClassLoader* class_loader,
3119 bool is_static) {
3120 Field* resolved = dex_cache->GetResolvedField(field_idx);
3121 if (resolved != NULL) {
3122 return resolved;
3123 }
3124 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3125 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3126 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003127 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003128 return NULL;
3129 }
3130
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003131 const char* name = dex_file.GetFieldName(field_id);
3132 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003133 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003134 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003135 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003136 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003137 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003138 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003139 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003140 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08003141 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
3142 }
3143 return resolved;
3144}
3145
3146Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
3147 uint32_t field_idx,
3148 DexCache* dex_cache,
3149 const ClassLoader* class_loader) {
3150 Field* resolved = dex_cache->GetResolvedField(field_idx);
3151 if (resolved != NULL) {
3152 return resolved;
3153 }
3154 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3155 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3156 if (klass == NULL) {
3157 DCHECK(Thread::Current()->IsExceptionPending());
3158 return NULL;
3159 }
3160
3161 const char* name = dex_file.GetFieldName(field_id);
3162 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3163 resolved = klass->FindField(name, type);
3164 if (resolved != NULL) {
3165 dex_cache->SetResolvedField(field_idx, resolved);
3166 } else {
3167 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003168 }
3169 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07003170}
3171
Ian Rogersad25ac52011-10-04 19:13:33 -07003172const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
3173 Class* declaring_class = referrer->GetDeclaringClass();
3174 DexCache* dex_cache = declaring_class->GetDexCache();
3175 const DexFile& dex_file = FindDexFile(dex_cache);
3176 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3177 return dex_file.GetShorty(method_id.proto_idx_);
3178}
3179
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003180void ClassLinker::DumpAllClasses(int flags) const {
3181 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3182 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3183 std::vector<Class*> all_classes;
3184 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003185 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003186 typedef Table::const_iterator It; // TODO: C++0x auto
3187 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3188 all_classes.push_back(it->second);
3189 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003190 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3191 all_classes.push_back(it->second);
3192 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003193 }
3194
3195 for (size_t i = 0; i < all_classes.size(); ++i) {
3196 all_classes[i]->DumpClass(std::cerr, flags);
3197 }
3198}
3199
Elliott Hughescac6cc72011-11-03 20:31:21 -07003200void ClassLinker::DumpForSigQuit(std::ostream& os) const {
3201 MutexLock mu(classes_lock_);
3202 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3203 << classes_.size() << " allocated classes\n";
3204}
3205
Elliott Hughese27955c2011-08-26 15:21:24 -07003206size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003207 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003208 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003209}
3210
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003211pid_t ClassLinker::GetClassesLockOwner() {
3212 return classes_lock_.GetOwner();
3213}
3214
3215pid_t ClassLinker::GetDexLockOwner() {
3216 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003217}
3218
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003219void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3220 DCHECK(!init_done_);
3221
3222 DCHECK(klass != NULL);
3223 DCHECK(klass->GetClassLoader() == NULL);
3224
3225 DCHECK(class_roots_ != NULL);
3226 DCHECK(class_roots_->Get(class_root) == NULL);
3227 class_roots_->Set(class_root, klass);
3228}
3229
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003230} // namespace art