blob: b18b31f65d37f88fde0344020f094a1b67cc99d8 [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 "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070036#include "intern_table.h"
Ian Rogers0571d352011-11-03 19:51:38 -070037#include "leb128.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070038#include "logging.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070039#include "oat_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070040#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080041#include "object_utils.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080042#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070043#include "runtime.h"
Ian Rogers466bb252011-10-14 03:29:56 -070044#include "runtime_support.h"
TDYa1275bb86012012-04-11 05:57:28 -070045#if defined(ART_USE_LLVM_COMPILER)
46#include "compiler_llvm/runtime_support_llvm.h"
47#endif
Elliott Hughes4d0207c2011-10-03 19:14:34 -070048#include "ScopedLocalRef.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070049#include "space.h"
Brian Carlstrom40381fb2011-10-19 14:13:40 -070050#include "stack_indirect_reference_table.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070051#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070052#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070053#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070054#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070055#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070056
57namespace art {
58
Elliott Hughes0512f022012-03-15 22:10:52 -070059static void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
60static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070061 va_list args;
62 va_start(args, fmt);
63 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
64 va_end(args);
65}
66
Elliott Hughes0512f022012-03-15 22:10:52 -070067static void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
68static void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070069 va_list args;
70 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070071 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070072 va_end(args);
73}
74
Elliott Hughes0512f022012-03-15 22:10:52 -070075static void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
76static void ThrowLinkageError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070077 va_list args;
78 va_start(args, fmt);
79 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
80 va_end(args);
81}
82
Elliott Hughes0512f022012-03-15 22:10:52 -070083static void ThrowNoSuchMethodError(bool is_direct, Class* c, const StringPiece& name,
84 const StringPiece& signature) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080085 ClassHelper kh(c);
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070086 std::ostringstream msg;
Ian Rogersc8b306f2012-02-17 21:34:44 -080087 msg << "no " << (is_direct ? "direct" : "virtual") << " method " << name << signature
Ian Rogers9f1ab122011-12-12 08:52:43 -080088 << " in class " << kh.GetDescriptor() << " or its superclasses";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080089 std::string location(kh.GetLocation());
90 if (!location.empty()) {
91 msg << " (defined in " << location << ")";
Elliott Hughescc5f9a92011-09-28 19:17:29 -070092 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070093 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070094}
95
Elliott Hughes0512f022012-03-15 22:10:52 -070096static void ThrowNoSuchFieldError(const StringPiece& scope, Class* c, const StringPiece& type,
97 const StringPiece& name) {
Ian Rogers9f1ab122011-12-12 08:52:43 -080098 ClassHelper kh(c);
99 std::ostringstream msg;
Ian Rogersb067ac22011-12-13 18:05:09 -0800100 msg << "no " << scope << "field " << name << " of type " << type
Ian Rogers9f1ab122011-12-12 08:52:43 -0800101 << " in class " << kh.GetDescriptor() << " or its superclasses";
102 std::string location(kh.GetLocation());
103 if (!location.empty()) {
104 msg << " (defined in " << location << ")";
105 }
106 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchFieldError;", msg.str().c_str());
107}
108
Elliott Hughes0512f022012-03-15 22:10:52 -0700109static void ThrowNullPointerException(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
110static void ThrowNullPointerException(const char* fmt, ...) {
Ian Rogerscab01012012-01-10 17:35:46 -0800111 va_list args;
112 va_start(args, fmt);
113 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NullPointerException;", fmt, args);
114 va_end(args);
115}
116
Elliott Hughes0512f022012-03-15 22:10:52 -0700117static void ThrowEarlierClassFailure(Class* c) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700118 // The class failed to initialize on a previous attempt, so we want to throw
119 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
120 // failed in verification, in which case v2 5.4.1 says we need to re-throw
121 // the previous error.
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700122 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
123
Elliott Hughes5c599942012-06-13 16:45:05 -0700124 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700125 if (c->GetVerifyErrorClass() != NULL) {
126 // TODO: change the verifier to store an _instance_, with a useful detail message?
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800127 ClassHelper ve_ch(c->GetVerifyErrorClass());
128 std::string error_descriptor(ve_ch.GetDescriptor());
129 Thread::Current()->ThrowNewException(error_descriptor.c_str(), PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700130 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800131 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700132 }
133}
134
Elliott Hughes0512f022012-03-15 22:10:52 -0700135static void WrapExceptionInInitializer() {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700136 Thread* self = Thread::Current();
137 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700138
139 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
140 CHECK(cause.get() != NULL);
141
142 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700143 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
144 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700145
Elliott Hughesa4f94742012-05-29 16:28:38 -0700146 // We only wrap non-Error exceptions; an Error can just be used as-is.
147 if (!is_error) {
148 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", NULL);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700149 }
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700150}
151
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800152static size_t Hash(const char* s) {
153 // This is the java.lang.String hashcode for convenience, not interoperability.
154 size_t hash = 0;
155 for (; *s != '\0'; ++s) {
156 hash = hash * 31 + *s;
157 }
158 return hash;
159}
160
Elliott Hughes418d20f2011-09-22 14:00:39 -0700161const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700162 "Ljava/lang/Class;",
163 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700164 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700165 "[Ljava/lang/Object;",
166 "Ljava/lang/String;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700167 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700168 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700169 "Ljava/lang/reflect/Field;",
170 "Ljava/lang/reflect/Method;",
Ian Rogers466bb252011-10-14 03:29:56 -0700171 "Ljava/lang/reflect/Proxy;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700172 "Ljava/lang/ClassLoader;",
173 "Ldalvik/system/BaseDexClassLoader;",
174 "Ldalvik/system/PathClassLoader;",
Ian Rogers5167c972012-02-03 10:41:20 -0800175 "Ljava/lang/Throwable;",
jeffhao8cd6dda2012-02-22 10:15:34 -0800176 "Ljava/lang/ClassNotFoundException;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700177 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700178 "Z",
179 "B",
180 "C",
181 "D",
182 "F",
183 "I",
184 "J",
185 "S",
186 "V",
187 "[Z",
188 "[B",
189 "[C",
190 "[D",
191 "[F",
192 "[I",
193 "[J",
194 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700195 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700196};
197
Brian Carlstroma004aa92012-02-08 18:05:09 -0800198ClassLinker* ClassLinker::CreateFromCompiler(const std::vector<const DexFile*>& boot_class_path,
199 InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700200 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800201 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800202 class_linker->InitFromCompiler(boot_class_path);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700203 return class_linker.release();
204}
205
Brian Carlstroma004aa92012-02-08 18:05:09 -0800206ClassLinker* ClassLinker::CreateFromImage(InternTable* intern_table) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800207 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700208 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700209 return class_linker.release();
210}
211
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800212ClassLinker::ClassLinker(InternTable* intern_table)
213 : dex_lock_("ClassLinker dex lock"),
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700214 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700215 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700216 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700217 init_done_(false),
218 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700219 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700220}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700221
Brian Carlstroma004aa92012-02-08 18:05:09 -0800222void ClassLinker::InitFromCompiler(const std::vector<const DexFile*>& boot_class_path) {
223 VLOG(startup) << "ClassLinker::Init";
224 CHECK(Runtime::Current()->IsCompiler());
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700225
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700226 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700227
Elliott Hughes30646832011-10-13 16:59:46 -0700228 // java_lang_Class comes first, it's needed for AllocClass
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800229 Heap* heap = Runtime::Current()->GetHeap();
230 SirtRef<Class> java_lang_Class(down_cast<Class*>(heap->AllocObject(NULL, sizeof(ClassClass))));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700231 CHECK(java_lang_Class.get() != NULL);
232 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700233 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700234 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700235
Elliott Hughes418d20f2011-09-22 14:00:39 -0700236 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700237 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
238 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700239
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700240 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700241 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
242 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700243 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700244 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700245 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700246
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700247 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700248 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
249 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700250
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700251 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700252 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700253
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700254 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700255 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
256 char_array_class->SetComponentType(char_class.get());
257 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700258
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700259 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700260 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
261 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700262 java_lang_String->SetObjectSize(sizeof(String));
263 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400264
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700265 // Create storage for root classes, save away our work so far (requires
266 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700267 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700268 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700269 SetClassRoot(kJavaLangClass, java_lang_Class.get());
270 SetClassRoot(kJavaLangObject, java_lang_Object.get());
271 SetClassRoot(kClassArrayClass, class_array_class.get());
272 SetClassRoot(kObjectArrayClass, object_array_class.get());
273 SetClassRoot(kCharArrayClass, char_array_class.get());
274 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700275
276 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700277 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
278 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
279 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
280 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
281 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
282 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
283 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
284 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700285
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700286 // Create array interface entries to populate once we can load system classes
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700287 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700288
289 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700290 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700291 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700292 IntArray::SetArrayClass(int_array_class.get());
293 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700294
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700295 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700296
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700297 // setup boot_class_path_ and register class_path now that we can
298 // use AllocObjectArray to create DexCache instances
Brian Carlstroma004aa92012-02-08 18:05:09 -0800299 CHECK_NE(0U, boot_class_path.size());
300 for (size_t i = 0; i != boot_class_path.size(); ++i) {
301 const DexFile* dex_file = boot_class_path[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700302 CHECK(dex_file != NULL);
303 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700304 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700305
Elliott Hughes80609252011-09-23 17:24:51 -0700306 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700307 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700308 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700309 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700310 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700311 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
312
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700313 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
314 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700315 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700316 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700317 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700318 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700319
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700320 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700321 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700322 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700323 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700324 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700325 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700326
327 // now we can use FindSystemClass
328
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700329 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700330 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700331 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700332
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700333 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700334 java_lang_Object->SetStatus(Class::kStatusNotReady);
335 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700336 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700337 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
338 java_lang_String->SetStatus(Class::kStatusNotReady);
339 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700340 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700341 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
342
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700343 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700344 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
345 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
346
347 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
348 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
349
350 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700351 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700352
353 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
354 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
355
356 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700357 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700358
359 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
360 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
361
362 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
363 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
364
365 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
366 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
367
Elliott Hughes418d20f2011-09-22 14:00:39 -0700368 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700369 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700370
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700371 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700372 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700373
374 // Setup the single, global copies of "interfaces" and "iftable"
375 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
376 CHECK(java_lang_Cloneable != NULL);
377 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
378 CHECK(java_io_Serializable != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700379 // We assume that Cloneable/Serializable don't have superinterfaces --
380 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700381 // supers as well.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800382 array_iftable_->Set(0, AllocInterfaceEntry(java_lang_Cloneable));
383 array_iftable_->Set(1, AllocInterfaceEntry(java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700384
Elliott Hughes418d20f2011-09-22 14:00:39 -0700385 // Sanity check Class[] and Object[]'s interfaces
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800386 ClassHelper kh(class_array_class.get(), this);
Ian Rogersd24e2642012-06-06 21:21:43 -0700387 CHECK_EQ(java_lang_Cloneable, kh.GetDirectInterface(0));
388 CHECK_EQ(java_io_Serializable, kh.GetDirectInterface(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800389 kh.ChangeClass(object_array_class.get());
Ian Rogersd24e2642012-06-06 21:21:43 -0700390 CHECK_EQ(java_lang_Cloneable, kh.GetDirectInterface(0));
391 CHECK_EQ(java_io_Serializable, kh.GetDirectInterface(1));
Elliott Hughes80609252011-09-23 17:24:51 -0700392 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700393 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700394 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700395 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700396
Elliott Hughes80609252011-09-23 17:24:51 -0700397 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
398 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700399 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700400
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700401 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700402 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700403 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700404
405 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700406 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700407 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700408
Ian Rogers466bb252011-10-14 03:29:56 -0700409 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
410
411 // Create java.lang.reflect.Proxy root
412 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
413 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
414
Brian Carlstrom1f870082011-08-23 16:02:11 -0700415 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700416 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
417 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700418 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700419 java_lang_ref_FinalizerReference->SetAccessFlags(
420 java_lang_ref_FinalizerReference->GetAccessFlags() |
421 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700422 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700423 java_lang_ref_PhantomReference->SetAccessFlags(
424 java_lang_ref_PhantomReference->GetAccessFlags() |
425 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700426 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700427 java_lang_ref_SoftReference->SetAccessFlags(
428 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700429 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700430 java_lang_ref_WeakReference->SetAccessFlags(
431 java_lang_ref_WeakReference->GetAccessFlags() |
432 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700433
Brian Carlstromaded5f72011-10-07 17:15:04 -0700434 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700435 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700436 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700437 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
438
439 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
440 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
441 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
442
443 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
444 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
445 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
446 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
447
jeffhao8cd6dda2012-02-22 10:15:34 -0800448 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
449 // java.lang.StackTraceElement as a convenience
Ian Rogers5167c972012-02-03 10:41:20 -0800450 SetClassRoot(kJavaLangThrowable, FindSystemClass("Ljava/lang/Throwable;"));
451 Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
jeffhao8cd6dda2012-02-22 10:15:34 -0800452 SetClassRoot(kJavaLangClassNotFoundException, FindSystemClass("Ljava/lang/ClassNotFoundException;"));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700453 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
454 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700455 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700456
Brian Carlstroma663ea52011-08-19 23:33:41 -0700457 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700458
Brian Carlstroma004aa92012-02-08 18:05:09 -0800459 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700460}
461
462void ClassLinker::FinishInit() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800463 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700464
465 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700466 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700467 // as the types of the field can't be resolved prior to the runtime being
468 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700469 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700470 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700471 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
472
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800473 const DexFile& java_lang_dex = FindDexFile(java_lang_ref_Reference->GetDexCache());
474
Brian Carlstrom16192862011-09-12 17:50:06 -0700475 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800476 FieldHelper fh(pendingNext, this);
477 CHECK_STREQ(fh.GetName(), "pendingNext");
478 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
479 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700480
481 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800482 fh.ChangeField(queue);
483 CHECK_STREQ(fh.GetName(), "queue");
484 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
485 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700486
487 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800488 fh.ChangeField(queueNext);
489 CHECK_STREQ(fh.GetName(), "queueNext");
490 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
491 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700492
493 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800494 fh.ChangeField(referent);
495 CHECK_STREQ(fh.GetName(), "referent");
496 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
497 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700498
499 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800500 fh.ChangeField(zombie);
501 CHECK_STREQ(fh.GetName(), "zombie");
502 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
503 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700504
Elliott Hughesa4f94742012-05-29 16:28:38 -0700505 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800506 heap->SetReferenceOffsets(referent->GetOffset(),
Brian Carlstrom16192862011-09-12 17:50:06 -0700507 queue->GetOffset(),
508 queueNext->GetOffset(),
509 pendingNext->GetOffset(),
510 zombie->GetOffset());
511
Brian Carlstroma663ea52011-08-19 23:33:41 -0700512 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700513 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700514 ClassRoot class_root = static_cast<ClassRoot>(i);
515 Class* klass = GetClassRoot(class_root);
516 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700517 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700518 // note SetClassRoot does additional validation.
519 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700520 }
521
Elliott Hughes92f14b22011-10-06 12:29:54 -0700522 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700523
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700524 // disable the slow paths in FindClass and CreatePrimitiveClass now
525 // that Object, Class, and Object[] are setup
526 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700527
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800528 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700529}
530
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700531void ClassLinker::RunRootClinits() {
532 Thread* self = Thread::Current();
533 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
534 Class* c = GetClassRoot(ClassRoot(i));
535 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Ian Rogers0045a292012-03-31 21:08:41 -0700536 EnsureInitialized(GetClassRoot(ClassRoot(i)), true, true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700537 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700538 }
539 }
540}
541
Brian Carlstromd601af82012-01-06 10:15:19 -0800542bool ClassLinker::GenerateOatFile(const std::string& dex_filename,
543 int oat_fd,
544 const std::string& oat_cache_filename) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800545 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -0700546 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800547 const char* dex2oat = dex2oat_string.c_str();
548
Brian Carlstroma004aa92012-02-08 18:05:09 -0800549 const char* class_path = Runtime::Current()->GetClassPathString().c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800550
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800551 Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800552 std::string boot_image_option_string("--boot-image=");
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700553 boot_image_option_string += heap->GetImageSpace()->GetImageFilename();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800554 const char* boot_image_option = boot_image_option_string.c_str();
555
556 std::string dex_file_option_string("--dex-file=");
Brian Carlstromd601af82012-01-06 10:15:19 -0800557 dex_file_option_string += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800558 const char* dex_file_option = dex_file_option_string.c_str();
559
Brian Carlstromd601af82012-01-06 10:15:19 -0800560 std::string oat_fd_option_string("--oat-fd=");
Brian Carlstrom866c8622012-01-06 16:35:13 -0800561 StringAppendF(&oat_fd_option_string, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800562 const char* oat_fd_option = oat_fd_option_string.c_str();
563
Brian Carlstroma004aa92012-02-08 18:05:09 -0800564 std::string oat_location_option_string("--oat-location=");
565 oat_location_option_string += oat_cache_filename;
566 const char* oat_location_option = oat_location_option_string.c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800567
jeffhao262bf462011-10-20 18:36:32 -0700568 // fork and exec dex2oat
569 pid_t pid = fork();
570 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800571 // no allocation allowed between fork and exec
Ian Rogers725aee52012-01-11 11:56:56 -0800572
573 // change process groups, so we don't get reaped by ProcessManager
574 setpgid(0, 0);
575
jeffhao10037c82012-01-23 15:06:23 -0800576 VLOG(class_linker) << dex2oat
577 << " --runtime-arg -Xms64m"
578 << " --runtime-arg -Xmx64m"
579 << " --runtime-arg -classpath"
580 << " --runtime-arg " << class_path
581 << " " << boot_image_option
582 << " " << dex_file_option
583 << " " << oat_fd_option
Brian Carlstroma004aa92012-02-08 18:05:09 -0800584 << " " << oat_location_option;
jeffhao10037c82012-01-23 15:06:23 -0800585
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800586 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700587 "--runtime-arg", "-Xms64m",
588 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500589 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800590 "--runtime-arg", class_path,
591 boot_image_option,
592 dex_file_option,
Brian Carlstromd601af82012-01-06 10:15:19 -0800593 oat_fd_option,
Brian Carlstroma004aa92012-02-08 18:05:09 -0800594 oat_location_option,
jeffhao262bf462011-10-20 18:36:32 -0700595 NULL);
596
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800597 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
Brian Carlstromd601af82012-01-06 10:15:19 -0800598 return false;
jeffhao262bf462011-10-20 18:36:32 -0700599 } else {
600 // wait for dex2oat to finish
601 int status;
602 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
603 if (got_pid != pid) {
604 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
Brian Carlstromd601af82012-01-06 10:15:19 -0800605 return false;
jeffhao262bf462011-10-20 18:36:32 -0700606 }
607 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800608 LOG(ERROR) << dex2oat << " failed with dex-file=" << dex_filename;
609 return false;
jeffhao262bf462011-10-20 18:36:32 -0700610 }
611 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800612 return true;
jeffhao262bf462011-10-20 18:36:32 -0700613}
614
Brian Carlstrom866c8622012-01-06 16:35:13 -0800615void ClassLinker::RegisterOatFile(const OatFile& oat_file) {
616 MutexLock mu(dex_lock_);
617 RegisterOatFileLocked(oat_file);
618}
619
620void ClassLinker::RegisterOatFileLocked(const OatFile& oat_file) {
621 dex_lock_.AssertHeld();
622 oat_files_.push_back(&oat_file);
623}
624
Ian Rogers30fab402012-01-23 15:43:46 -0800625OatFile* ClassLinker::OpenOat(const ImageSpace* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700626 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700627 const Runtime* runtime = Runtime::Current();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700628 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800629 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
630 // check the down cast
631 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700632 std::string oat_filename;
633 oat_filename += runtime->GetHostPrefix();
634 oat_filename += oat_location->ToModifiedUtf8();
Logan Chien0c717dd2012-03-28 18:31:07 +0800635 OatFile* oat_file = OatFile::Open(oat_filename, oat_filename,
636 image_header.GetOatBegin(),
637 OatFile::kRelocNone);
Ian Rogers30fab402012-01-23 15:43:46 -0800638 VLOG(startup) << "ClassLinker::OpenOat entering oat_filename=" << oat_filename;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700639 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700640 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700641 return NULL;
642 }
643 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
644 uint32_t image_oat_checksum = image_header.GetOatChecksum();
645 if (oat_checksum != image_oat_checksum) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800646 LOG(ERROR) << "Failed to match oat file checksum " << std::hex << oat_checksum
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700647 << " to expected oat checksum " << std::hex << oat_checksum
648 << " in image";
649 return NULL;
650 }
Brian Carlstrom866c8622012-01-06 16:35:13 -0800651 RegisterOatFileLocked(*oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800652 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700653 return oat_file;
654}
655
Brian Carlstromae826982011-11-09 01:33:42 -0800656const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800657 return FindOpenedOatFileFromDexLocation(dex_file.GetLocation());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800658}
659
Brian Carlstroma004aa92012-02-08 18:05:09 -0800660const OatFile* ClassLinker::FindOpenedOatFileFromDexLocation(const std::string& dex_location) {
Elliott Hughesf8349362012-06-18 15:00:06 -0700661 MutexLock mu(dex_lock_);
Brian Carlstromae826982011-11-09 01:33:42 -0800662 for (size_t i = 0; i < oat_files_.size(); i++) {
663 const OatFile* oat_file = oat_files_[i];
664 DCHECK(oat_file != NULL);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800665 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, false);
Brian Carlstroma004aa92012-02-08 18:05:09 -0800666 if (oat_dex_file != NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800667 return oat_file;
668 }
669 }
670 return NULL;
671}
672
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800673static const DexFile* FindDexFileInOatLocation(const std::string& dex_location,
674 uint32_t dex_location_checksum,
675 const std::string& oat_location) {
Logan Chien0c717dd2012-03-28 18:31:07 +0800676 UniquePtr<OatFile> oat_file(
677 OatFile::Open(oat_location, oat_location, NULL, OatFile::kRelocAll));
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800678 if (oat_file.get() == NULL) {
679 return NULL;
680 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700681 Runtime* runtime = Runtime::Current();
682 const ImageHeader& image_header = runtime->GetHeap()->GetImageSpace()->GetImageHeader();
683 if (oat_file->GetOatHeader().GetImageFileLocationChecksum() != image_header.GetOatChecksum()) {
684 return NULL;
685 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800686 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
687 if (oat_dex_file == NULL) {
688 return NULL;
689 }
690 if (oat_dex_file->GetDexFileLocationChecksum() != dex_location_checksum) {
691 return NULL;
692 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700693 runtime->GetClassLinker()->RegisterOatFile(*oat_file.release());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800694 return oat_dex_file->OpenDexFile();
695}
696
697const DexFile* ClassLinker::FindOrCreateOatFileForDexLocation(const std::string& dex_location,
698 const std::string& oat_location) {
699 uint32_t dex_location_checksum;
700 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) {
701 LOG(ERROR) << "Failed to compute checksum '" << dex_location << "'";
702 return NULL;
703 }
704
705 // Check if we already have an up-to-date output file
706 const DexFile* dex_file = FindDexFileInOatLocation(dex_location,
707 dex_location_checksum,
708 oat_location);
709 if (dex_file != NULL) {
710 return dex_file;
711 }
712
713 // Generate the output oat file for the dex file
714 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
715 UniquePtr<File> file(OS::OpenFile(oat_location.c_str(), true));
716 if (file.get() == NULL) {
717 LOG(ERROR) << "Failed to create oat file: " << oat_location;
718 return NULL;
719 }
720 if (!class_linker->GenerateOatFile(dex_location, file->Fd(), oat_location)) {
721 LOG(ERROR) << "Failed to generate oat file: " << oat_location;
722 return NULL;
723 }
724 // Open the oat from file descriptor we passed to GenerateOatFile
725 if (lseek(file->Fd(), 0, SEEK_SET) != 0) {
726 LOG(ERROR) << "Failed to seek to start of generated oat file: " << oat_location;
727 return NULL;
728 }
Logan Chien0c717dd2012-03-28 18:31:07 +0800729 const OatFile* oat_file =
730 OatFile::Open(*file.get(), oat_location, NULL, OatFile::kRelocAll);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800731 if (oat_file == NULL) {
732 LOG(ERROR) << "Failed to open generated oat file: " << oat_location;
733 return NULL;
734 }
735 class_linker->RegisterOatFile(*oat_file);
736 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
737 if (oat_dex_file == NULL) {
738 LOG(ERROR) << "Failed to find dex file in generated oat file: " << oat_location;
739 return NULL;
740 }
741 return oat_dex_file->OpenDexFile();
742}
743
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700744const DexFile* ClassLinker::VerifyOatFileChecksums(const OatFile* oat_file,
745 const std::string& dex_location,
746 uint32_t dex_location_checksum) {
747 Runtime* runtime = Runtime::Current();
748 const ImageHeader& image_header = runtime->GetHeap()->GetImageSpace()->GetImageHeader();
749 uint32_t image_checksum = image_header.GetOatChecksum();
750 bool image_check = (oat_file->GetOatHeader().GetImageFileLocationChecksum() == image_checksum);
751
752 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
753 CHECK(oat_dex_file != NULL) << oat_file->GetLocation() << " " << dex_location;
754 bool dex_check = (dex_location_checksum == oat_dex_file->GetDexFileLocationChecksum());
755
756 if (image_check && dex_check) {
757 RegisterOatFileLocked(*oat_file);
758 return oat_file->GetOatDexFile(dex_location)->OpenDexFile();
759 }
760
761 if (!image_check) {
762 std::string image_file(image_header.GetImageRoot(
763 ImageHeader::kOatLocation)->AsString()->ToModifiedUtf8());
764 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
765 << " checksum ( " << std::hex << oat_dex_file->GetDexFileLocationChecksum()
766 << ") mismatch with " << image_file
767 << " (" << std::hex << image_checksum << ")";
768 }
769 if (!dex_check) {
770 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
771 << " checksum ( " << std::hex << oat_dex_file->GetDexFileLocationChecksum()
772 << ") mismatch with " << dex_location
773 << " (" << std::hex << dex_location_checksum << ")";
774 }
775 return NULL;
776}
777
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800778const DexFile* ClassLinker::FindDexFileInOatFileFromDexLocation(const std::string& dex_location) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700779 MutexLock mu(dex_lock_);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800780
Brian Carlstroma004aa92012-02-08 18:05:09 -0800781 const OatFile* open_oat_file = FindOpenedOatFileFromDexLocation(dex_location);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800782 if (open_oat_file != NULL) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800783 return open_oat_file->GetOatDexFile(dex_location)->OpenDexFile();
Brian Carlstromae826982011-11-09 01:33:42 -0800784 }
785
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700786 // Look for an existing file next to dex. for example, for
787 // /foo/bar/baz.jar, look for /foo/bar/baz.jar.oat.
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800788 std::string oat_filename(OatFile::DexFilenameToOatFilename(dex_location));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800789 const OatFile* oat_file = FindOatFileFromOatLocation(oat_filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800790 if (oat_file != NULL) {
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700791 uint32_t dex_location_checksum;
792 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) {
793 // If no classes.dex found in dex_location, it has been stripped, assume oat is up-to-date.
794 // This is the common case in user builds for jar's and apk's in the /system directory.
795 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
796 CHECK(oat_dex_file != NULL) << oat_filename << " " << dex_location;
797 RegisterOatFileLocked(*oat_file);
798 return oat_dex_file->OpenDexFile();
799 }
800 const DexFile* dex_file = VerifyOatFileChecksums(oat_file,
801 dex_location,
802 dex_location_checksum);
803 if (dex_file != NULL) {
804 return dex_file;
805 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800806 }
807 // Look for an existing file in the art-cache, validating the result if found
808 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
809 std::string cache_location(GetArtCacheFilenameOrDie(oat_filename));
810 oat_file = FindOatFileFromOatLocation(cache_location);
811 if (oat_file != NULL) {
812 uint32_t dex_location_checksum;
813 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) {
814 LOG(WARNING) << "Failed to compute checksum: " << dex_location;
815 return NULL;
816 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700817 const DexFile* dex_file = VerifyOatFileChecksums(oat_file,
818 dex_location,
819 dex_location_checksum);
820 if (dex_file != NULL) {
821 return dex_file;
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700822 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800823 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
Brian Carlstrom5ef74932012-03-23 17:56:02 -0700824 PLOG(FATAL) << "Failed to remove obsolete .oat file " << oat_file->GetLocation();
Brian Carlstromd601af82012-01-06 10:15:19 -0800825 }
jeffhao262bf462011-10-20 18:36:32 -0700826 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800827 LOG(INFO) << "Failed to open oat file from " << oat_filename << " or " << cache_location << ".";
828
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800829 // Try to generate oat file if it wasn't found or was obsolete.
830 std::string oat_cache_filename(GetArtCacheFilenameOrDie(oat_filename));
831 return FindOrCreateOatFileForDexLocation(dex_location, oat_cache_filename);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700832}
833
Brian Carlstromae826982011-11-09 01:33:42 -0800834const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Elliott Hughesf8349362012-06-18 15:00:06 -0700835 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700836 for (size_t i = 0; i < oat_files_.size(); i++) {
837 const OatFile* oat_file = oat_files_[i];
838 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800839 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700840 return oat_file;
841 }
842 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700843 return NULL;
844}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700845
Brian Carlstromae826982011-11-09 01:33:42 -0800846const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
jeffhaof6174e82012-01-31 16:14:17 -0800847 MutexLock mu(dex_lock_);
848 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
849 if (oat_file != NULL) {
850 return oat_file;
851 }
852
Logan Chien0c717dd2012-03-28 18:31:07 +0800853 oat_file = OatFile::Open(oat_location, oat_location, NULL,
854 OatFile::kRelocAll);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700855 if (oat_file == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800856 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700857 }
Brian Carlstromae826982011-11-09 01:33:42 -0800858 CHECK(oat_file != NULL) << oat_location;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700859 return oat_file;
860}
861
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700862void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800863 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700864 CHECK(!init_done_);
865
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800866 Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700867 ImageSpace* space = heap->GetImageSpace();
868 OatFile* oat_file = OpenOat(space);
869 CHECK(oat_file != NULL) << "Failed to open oat file for image";
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700870 CHECK_EQ(oat_file->GetOatHeader().GetImageFileLocationChecksum(), 0U);
Elliott Hughes74847412012-06-20 18:10:21 -0700871 CHECK(oat_file->GetOatHeader().GetImageFileLocation().empty());
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700872 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
873 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700874
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700875 // Special case of setting up the String class early so that we can test arbitrary objects
876 // as being Strings or not
877 Class* java_lang_String = space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
878 ->AsObjectArray<Class>()->Get(kJavaLangString);
879 String::SetClass(java_lang_String);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800880
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700881 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
882 static_cast<uint32_t>(dex_caches->GetLength()));
883 for (int i = 0; i < dex_caches->GetLength(); i++) {
884 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
885 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
886 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
887 const DexFile* dex_file = oat_dex_file->OpenDexFile();
888 if (dex_file == NULL) {
889 LOG(FATAL) << "Failed to open dex file " << dex_file_location
890 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700891 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700892
893 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
894
895 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700896 }
897
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800898 HeapBitmap* heap_bitmap = heap->GetLiveBits();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700899 DCHECK(heap_bitmap != NULL);
900
Brian Carlstroma663ea52011-08-19 23:33:41 -0700901 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700902 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700903
904 // reinit class_roots_
Ian Rogers30fab402012-01-23 15:43:46 -0800905 Object* class_roots_object =
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700906 heap->GetImageSpace()->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700907 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700908
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800909 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700910 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
911 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800912 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700913 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700914 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700915 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
916 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
917 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
918 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
919 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
920 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
921 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
922 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700923 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Ian Rogers5167c972012-02-03 10:41:20 -0800924 Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700925 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700926
927 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700928
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800929 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700930}
931
Brian Carlstrom78128a62011-09-15 17:21:19 -0700932void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700933 DCHECK(obj != NULL);
934 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700935 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700936
Elliott Hughesdbb40792011-11-18 17:05:22 -0800937 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700938 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700939 return;
940 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700941 if (obj->IsClass()) {
942 // restore class to ClassLinker::classes_ table
943 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800944 ClassHelper kh(klass, class_linker);
Brian Carlstrom07bb8552012-01-18 22:10:50 -0800945 Class* existing = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
946 DCHECK(existing == NULL) << kh.GetDescriptor();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700947 return;
948 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700949}
950
951// Keep in sync with InitCallback. Anything we visit, we need to
952// reinit references to when reinitializing a ClassLinker from a
953// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700954void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
955 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700956
Elliott Hughesf8349362012-06-18 15:00:06 -0700957 {
958 MutexLock mu(dex_lock_);
959 for (size_t i = 0; i < dex_caches_.size(); i++) {
960 visitor(dex_caches_[i], arg);
961 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700962 }
963
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700964 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700965 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700966 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700967 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700968 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700969 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700970
971 // We deliberately ignore the class roots in the image since we
972 // handle image roots by using the MS/CMS rescanning of dirty cards.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700973 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700974
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700975 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700976}
977
Elliott Hughesa2155262011-11-16 16:26:58 -0800978void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
979 MutexLock mu(classes_lock_);
980 typedef Table::const_iterator It; // TODO: C++0x auto
981 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
982 if (!visitor(it->second, arg)) {
983 return;
984 }
985 }
986 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
987 if (!visitor(it->second, arg)) {
988 return;
989 }
990 }
991}
992
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700993ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700994 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700995 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700996 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700997 BooleanArray::ResetArrayClass();
998 ByteArray::ResetArrayClass();
999 CharArray::ResetArrayClass();
1000 DoubleArray::ResetArrayClass();
1001 FloatArray::ResetArrayClass();
1002 IntArray::ResetArrayClass();
1003 LongArray::ResetArrayClass();
1004 ShortArray::ResetArrayClass();
1005 PathClassLoader::ResetClass();
Ian Rogers5167c972012-02-03 10:41:20 -08001006 Throwable::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001007 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001008 STLDeleteElements(&boot_class_path_);
1009 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001010}
1011
1012DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001013 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
1014 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001015 return NULL;
1016 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001017 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
1018 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001019 return NULL;
1020 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001021 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
1022 if (strings.get() == NULL) {
1023 return NULL;
1024 }
1025 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
1026 if (types.get() == NULL) {
1027 return NULL;
1028 }
1029 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
1030 if (methods.get() == NULL) {
1031 return NULL;
1032 }
1033 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
1034 if (fields.get() == NULL) {
1035 return NULL;
1036 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001037 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
1038 if (initialized_static_storage.get() == NULL) {
1039 return NULL;
1040 }
1041
1042 dex_cache->Init(location.get(),
1043 strings.get(),
1044 types.get(),
1045 methods.get(),
1046 fields.get(),
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001047 initialized_static_storage.get());
1048 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001049}
1050
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001051InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
1052 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001053 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
1054 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001055 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001056 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001057}
1058
Brian Carlstrom4873d462011-08-21 15:23:39 -07001059Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
1060 DCHECK_GE(class_size, sizeof(Class));
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001061 Heap* heap = Runtime::Current()->GetHeap();
1062 SirtRef<Class> klass(heap->AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001063 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001064 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001065 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001066}
1067
Brian Carlstrom4873d462011-08-21 15:23:39 -07001068Class* ClassLinker::AllocClass(size_t class_size) {
1069 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001070}
1071
Jesse Wilson35baaab2011-08-10 16:18:03 -04001072Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001073 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -07001074}
1075
1076Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001077 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001078}
1079
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001080ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
1081 return ObjectArray<StackTraceElement>::Alloc(
1082 GetClassRoot(kJavaLangStackTraceElementArrayClass),
1083 length);
1084}
1085
Elliott Hughes5c599942012-06-13 16:45:05 -07001086static Class* EnsureResolved(Class* klass) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001087 DCHECK(klass != NULL);
1088 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -07001089 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001090 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001091 ObjectLock lock(klass);
1092 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001093 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001094 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001095 PrettyDescriptor(klass).c_str());
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001096 klass->SetStatus(Class::kStatusError);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001097 return NULL;
1098 }
1099 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001100 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001101 lock.Wait();
1102 }
1103 }
1104 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001105 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001106 return NULL;
1107 }
1108 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001109 CHECK(klass->IsResolved()) << PrettyClass(klass);
1110 CHECK(!self->IsExceptionPending())
1111 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
1112 return klass;
1113}
1114
Elliott Hughesdb7d5e92011-12-16 18:47:37 -08001115Class* ClassLinker::FindSystemClass(const char* descriptor) {
1116 return FindClass(descriptor, NULL);
1117}
1118
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001119Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001120 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001121 Thread* self = Thread::Current();
1122 DCHECK(self != NULL);
1123 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001124 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001125 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1126 // for primitive classes that aren't backed by dex files.
1127 return FindPrimitiveClass(descriptor[0]);
1128 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001129 // Find the class in the loaded classes table.
1130 Class* klass = LookupClass(descriptor, class_loader);
1131 if (klass != NULL) {
1132 return EnsureResolved(klass);
1133 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001134 // Class is not yet loaded.
1135 if (descriptor[0] == '[') {
1136 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001137
Jesse Wilson47daf872011-11-23 11:42:45 -05001138 } else if (class_loader == NULL) {
1139 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1140 if (pair.second != NULL) {
1141 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1142 }
1143
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001144 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Jesse Wilson47daf872011-11-23 11:42:45 -05001145 // first try the boot class path
1146 Class* system_class = FindSystemClass(descriptor);
1147 if (system_class != NULL) {
1148 return system_class;
1149 }
1150 CHECK(self->IsExceptionPending());
1151 self->ClearException();
1152
1153 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001154 const std::vector<const DexFile*>& class_path
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001155 = Runtime::Current()->GetCompileTimeClassPath(class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001156 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001157 if (pair.second != NULL) {
1158 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001159 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001160
1161 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001162 std::string class_name_string(DescriptorToDot(descriptor));
Elliott Hughes34e06962012-04-09 13:55:55 -07001163 ScopedThreadStateChange tsc(self, kNative);
Elliott Hughes748382f2012-01-26 18:07:38 -08001164 JNIEnv* env = self->GetJniEnv();
Jesse Wilson47daf872011-11-23 11:42:45 -05001165 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1166 if (class_name_object.get() == NULL) {
1167 return NULL;
1168 }
1169 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
Elliott Hughes9c750f92012-04-05 12:07:59 -07001170 CHECK(class_loader_object.get() != NULL);
Elliott Hughesa4f94742012-05-29 16:28:38 -07001171 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(),
1172 WellKnownClasses::java_lang_ClassLoader_loadClass,
Ian Rogers761bfa82012-01-11 10:14:05 -08001173 class_name_object.get()));
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001174 if (env->ExceptionCheck()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001175 // If the ClassLoader threw, pass that exception up.
1176 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001177 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001178 // broken loader - throw NPE to be compatible with Dalvik
1179 ThrowNullPointerException("ClassLoader.loadClass returned null for %s",
1180 class_name_string.c_str());
1181 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001182 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08001183 // success, return Class*
Ian Rogers6b0870d2011-12-15 19:38:12 -08001184 return Decode<Class*>(env, result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001185 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001186 }
1187
Elliott Hughes82914b62012-04-09 15:56:29 -07001188 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001189 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001190}
1191
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001192Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001193 const ClassLoader* class_loader,
1194 const DexFile& dex_file,
1195 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001196 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001197 // Load the class from the dex file.
1198 if (!init_done_) {
1199 // finish up init of hand crafted class_roots_
1200 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001201 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001202 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001203 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001204 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001205 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001206 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001207 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001208 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001209 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001210 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001211 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001212 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001213 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001214 }
1215 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001216 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001217 }
1218 klass->SetDexCache(FindDexCache(dex_file));
1219 LoadClass(dex_file, dex_class_def, klass, class_loader);
1220 // Check for a pending exception during load
1221 Thread* self = Thread::Current();
1222 if (self->IsExceptionPending()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001223 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001224 return NULL;
1225 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001226 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001227 klass->SetClinitThreadId(self->GetTid());
1228 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom01e076e2012-03-30 11:54:16 -07001229 SirtRef<Class> existing(InsertClass(descriptor, klass.get(), false));
1230 if (existing.get() != NULL) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001231 // We failed to insert because we raced with another thread.
Brian Carlstrom01e076e2012-03-30 11:54:16 -07001232 return EnsureResolved(existing.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001233 }
1234 // Finish loading (if necessary) by finding parents
1235 CHECK(!klass->IsLoaded());
1236 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1237 // Loading failed.
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->IsLoaded());
1243 // Link the class (if necessary)
1244 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001245 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001246 // Linking failed.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001247 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001248 lock.NotifyAll();
1249 return NULL;
1250 }
1251 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001252
1253 /*
1254 * We send CLASS_PREPARE events to the debugger from here. The
1255 * definition of "preparation" is creating the static fields for a
1256 * class and initializing them to the standard default values, but not
1257 * executing any code (that comes later, during "initialization").
1258 *
1259 * We did the static preparation in LinkClass.
1260 *
1261 * The class has been prepared and resolved but possibly not yet verified
1262 * at this point.
1263 */
1264 Dbg::PostClassPrepare(klass.get());
1265
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001266 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001267}
1268
Brian Carlstrom4873d462011-08-21 15:23:39 -07001269// Precomputes size that will be needed for Class, matching LinkStaticFields
1270size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1271 const DexFile::ClassDef& dex_class_def) {
1272 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001273 size_t num_ref = 0;
1274 size_t num_32 = 0;
1275 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001276 if (class_data != NULL) {
1277 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1278 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001279 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001280 char c = descriptor[0];
1281 if (c == 'L' || c == '[') {
1282 num_ref++;
1283 } else if (c == 'J' || c == 'D') {
1284 num_64++;
1285 } else {
1286 num_32++;
1287 }
1288 }
1289 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001290 // start with generic class data
1291 size_t size = sizeof(Class);
1292 // follow with reference fields which must be contiguous at start
1293 size += (num_ref * sizeof(uint32_t));
1294 // if there are 64-bit fields to add, make sure they are aligned
1295 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1296 if (num_32 != 0) {
1297 // use an available 32-bit field for padding
1298 num_32--;
1299 }
1300 size += sizeof(uint32_t); // either way, we are adding a word
1301 DCHECK_EQ(size, RoundUp(size, 8));
1302 }
1303 // tack on any 64-bit fields now that alignment is assured
1304 size += (num_64 * sizeof(uint64_t));
1305 // tack on any remaining 32-bit fields
1306 size += (num_32 * sizeof(uint32_t));
1307 return size;
1308}
1309
Ian Rogers19846512012-02-24 11:42:47 -08001310const OatFile::OatClass* ClassLinker::GetOatClass(const DexFile& dex_file, const char* descriptor) {
1311 DCHECK(descriptor != NULL);
Ian Rogers19846512012-02-24 11:42:47 -08001312 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
1313 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << descriptor;
1314 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1315 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << descriptor;
1316 uint32_t class_def_index;
1317 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1318 CHECK(found) << dex_file.GetLocation() << " " << descriptor;
1319 const OatFile::OatClass* oat_class = oat_dex_file->GetOatClass(class_def_index);
1320 CHECK(oat_class != NULL) << dex_file.GetLocation() << " " << descriptor;
1321 return oat_class;
1322}
1323
TDYa12785321912012-04-01 15:24:56 -07001324const OatFile::OatMethod ClassLinker::GetOatMethodFor(const Method* method) {
Ian Rogers19846512012-02-24 11:42:47 -08001325 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08001326 // method for direct methods (or virtual methods made direct).
1327 Class* declaring_class = method->GetDeclaringClass();
1328 size_t oat_method_index;
1329 if (method->IsStatic() || method->IsDirect()) {
1330 // Simple case where the oat method index was stashed at load time.
1331 oat_method_index = method->GetMethodIndex();
1332 } else {
1333 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
1334 // by search for its position in the declared virtual methods.
1335 oat_method_index = declaring_class->NumDirectMethods();
1336 size_t end = declaring_class->NumVirtualMethods();
1337 bool found = false;
1338 for (size_t i = 0; i < end; i++) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08001339 if (declaring_class->GetVirtualMethod(i) == method) {
1340 found = true;
1341 break;
1342 }
Ian Rogersf320b632012-03-13 18:47:47 -07001343 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001344 }
1345 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method);
1346 }
1347 ClassHelper kh(declaring_class);
Ian Rogers19846512012-02-24 11:42:47 -08001348 UniquePtr<const OatFile::OatClass> oat_class(GetOatClass(kh.GetDexFile(), kh.GetDescriptor()));
Brian Carlstromf5822582012-03-19 22:34:31 -07001349 CHECK(oat_class.get() != NULL);
TDYa12785321912012-04-01 15:24:56 -07001350 return oat_class->GetOatMethod(oat_method_index);
1351}
1352
1353// Special case to get oat code without overwriting a trampoline.
1354const void* ClassLinker::GetOatCodeFor(const Method* method) {
TDYa127ccffd9e2012-04-08 14:37:03 -07001355 CHECK(Runtime::Current()->IsCompiler() || method->GetDeclaringClass()->IsInitializing());
TDYa12785321912012-04-01 15:24:56 -07001356 return GetOatMethodFor(method).GetCode();
1357}
1358
1359void ClassLinker::LinkOatCodeFor(Method* method) {
1360 Class* declaring_class = method->GetDeclaringClass();
1361 ClassHelper kh(declaring_class);
1362 const OatFile* oat_file = FindOpenedOatFileForDexFile(kh.GetDexFile());
1363 if (oat_file != NULL) {
1364 // NOTE: We have to check the availability of OatFile first. Because
1365 // GetOatMethodFor(...) will try to find the OatFile and there's
1366 // an assert in GetOatMethodFor(...). Besides, due to the return
1367 // type of OatClass::GetOatMethod(...), we can't return a failure value
1368 // back.
1369
1370 // TODO: Remove this workaround.
TDYa12705fe3b62012-04-21 00:28:54 -07001371 OatFile::OatMethod oat_method = GetOatMethodFor(method);
1372 if (method->GetCode() == NULL) {
1373 method->SetCode(oat_method.GetCode());
1374 }
1375 if (method->GetInvokeStub() == NULL) {
1376 method->SetInvokeStub(oat_method.GetInvokeStub());
1377 }
TDYa12785321912012-04-01 15:24:56 -07001378 }
Ian Rogers19846512012-02-24 11:42:47 -08001379}
1380
1381void ClassLinker::FixupStaticTrampolines(Class* klass) {
1382 ClassHelper kh(klass);
1383 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
1384 CHECK(dex_class_def != NULL);
1385 const DexFile& dex_file = kh.GetDexFile();
1386 const byte* class_data = dex_file.GetClassData(*dex_class_def);
1387 if (class_data == NULL) {
1388 return; // no fields or methods - for example a marker interface
1389 }
Brian Carlstromf5822582012-03-19 22:34:31 -07001390 if (!Runtime::Current()->IsStarted() || Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers19846512012-02-24 11:42:47 -08001391 // OAT file unavailable
1392 return;
1393 }
Brian Carlstromf5822582012-03-19 22:34:31 -07001394 UniquePtr<const OatFile::OatClass> oat_class(GetOatClass(dex_file, kh.GetDescriptor()));
1395 CHECK(oat_class.get() != NULL);
Ian Rogers19846512012-02-24 11:42:47 -08001396 ClassDataItemIterator it(dex_file, class_data);
1397 // Skip fields
1398 while (it.HasNextStaticField()) {
1399 it.Next();
1400 }
1401 while (it.HasNextInstanceField()) {
1402 it.Next();
1403 }
1404 size_t method_index = 0;
1405 // Link the code of methods skipped by LinkCode
1406 const void* trampoline = Runtime::Current()->GetResolutionStubArray(Runtime::kStaticMethod)->GetData();
1407 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1408 Method* method = klass->GetDirectMethod(i);
jeffhaob5e81852012-03-12 11:15:45 -07001409 if (Runtime::Current()->IsMethodTracingActive()) {
1410 Trace* tracer = Runtime::Current()->GetTracer();
1411 if (tracer->GetSavedCodeFromMap(method) == trampoline) {
1412 const void* code = oat_class->GetOatMethod(method_index).GetCode();
1413 tracer->ResetSavedCode(method);
1414 method->SetCode(code);
1415 tracer->SaveAndUpdateCode(method);
1416 }
1417 } else if (method->GetCode() == trampoline) {
Ian Rogers19846512012-02-24 11:42:47 -08001418 const void* code = oat_class->GetOatMethod(method_index).GetCode();
1419 CHECK(code != NULL);
1420 method->SetCode(code);
1421 }
1422 method_index++;
1423 }
1424}
1425
Elliott Hughes5c599942012-06-13 16:45:05 -07001426static void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001427 // Every kind of method should at least get an invoke stub from the oat_method.
1428 // non-abstract methods also get their code pointers.
1429 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001430 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001431
Ian Rogers19846512012-02-24 11:42:47 -08001432 Runtime* runtime = Runtime::Current();
Brian Carlstrom92827a52011-10-10 15:50:01 -07001433 if (method->IsAbstract()) {
Ian Rogers19846512012-02-24 11:42:47 -08001434 method->SetCode(runtime->GetAbstractMethodErrorStubArray()->GetData());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001435 return;
1436 }
Ian Rogers19846512012-02-24 11:42:47 -08001437
1438 if (method->IsStatic() && !method->IsConstructor()) {
1439 // For static methods excluding the class initializer, install the trampoline
1440 method->SetCode(runtime->GetResolutionStubArray(Runtime::kStaticMethod)->GetData());
Ian Rogers0d6de042012-02-29 08:50:26 -08001441 }
1442 if (method->IsNative()) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001443 // unregistering restores the dlsym lookup stub
Ian Rogers19846512012-02-24 11:42:47 -08001444 method->UnregisterNative(Thread::Current());
jeffhao26c0a1a2012-01-17 16:28:33 -08001445 }
1446
1447 if (Runtime::Current()->IsMethodTracingActive()) {
jeffhao26c0a1a2012-01-17 16:28:33 -08001448 Trace* tracer = Runtime::Current()->GetTracer();
jeffhaob5e81852012-03-12 11:15:45 -07001449 tracer->SaveAndUpdateCode(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001450 }
1451}
1452
Brian Carlstromf615a612011-07-23 12:50:34 -07001453void ClassLinker::LoadClass(const DexFile& dex_file,
1454 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001455 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001456 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001457 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001458 CHECK(klass->GetDexCache() != NULL);
1459 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001460 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001461 CHECK(descriptor != NULL);
1462
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001463 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001464 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001465 // Make sure that none of our runtime-only flags are set.
1466 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001467 klass->SetAccessFlags(access_flags);
1468 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001469 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001470 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001471
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001472 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001473
Ian Rogers0571d352011-11-03 19:51:38 -07001474 // Load fields fields.
1475 const byte* class_data = dex_file.GetClassData(dex_class_def);
1476 if (class_data == NULL) {
1477 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001478 }
Ian Rogers0571d352011-11-03 19:51:38 -07001479 ClassDataItemIterator it(dex_file, class_data);
1480 if (it.NumStaticFields() != 0) {
1481 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1482 }
1483 if (it.NumInstanceFields() != 0) {
1484 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1485 }
1486 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1487 SirtRef<Field> sfield(AllocField());
1488 klass->SetStaticField(i, sfield.get());
1489 LoadField(dex_file, it, klass, sfield);
1490 }
1491 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1492 SirtRef<Field> ifield(AllocField());
1493 klass->SetInstanceField(i, ifield.get());
1494 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001495 }
1496
Brian Carlstromf5822582012-03-19 22:34:31 -07001497 UniquePtr<const OatFile::OatClass> oat_class;
1498 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
1499 oat_class.reset(GetOatClass(dex_file, descriptor));
1500 }
Ian Rogers19846512012-02-24 11:42:47 -08001501
Ian Rogers0571d352011-11-03 19:51:38 -07001502 // Load methods.
1503 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001504 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001505 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001506 }
Ian Rogers0571d352011-11-03 19:51:38 -07001507 if (it.NumVirtualMethods() != 0) {
1508 // TODO: append direct methods to class object
1509 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001510 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08001511 size_t class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001512 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1513 SirtRef<Method> method(AllocMethod());
1514 klass->SetDirectMethod(i, method.get());
1515 LoadMethod(dex_file, it, klass, method);
1516 if (oat_class.get() != NULL) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08001517 LinkCode(method, oat_class.get(), class_def_method_index);
Ian Rogers0571d352011-11-03 19:51:38 -07001518 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08001519 method->SetMethodIndex(class_def_method_index);
1520 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001521 }
1522 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1523 SirtRef<Method> method(AllocMethod());
1524 klass->SetVirtualMethod(i, method.get());
1525 LoadMethod(dex_file, it, klass, method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08001526 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers0571d352011-11-03 19:51:38 -07001527 if (oat_class.get() != NULL) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08001528 LinkCode(method, oat_class.get(), class_def_method_index);
Ian Rogers0571d352011-11-03 19:51:38 -07001529 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08001530 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001531 }
1532 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001533}
1534
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001535void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Ian Rogers0571d352011-11-03 19:51:38 -07001536 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001537 uint32_t field_idx = it.GetMemberIndex();
1538 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001539 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001540 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001541}
1542
Ian Rogers0571d352011-11-03 19:51:38 -07001543void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1544 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers19846512012-02-24 11:42:47 -08001545 uint32_t dex_method_idx = it.GetMemberIndex();
1546 dst->SetDexMethodIndex(dex_method_idx);
1547 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001548 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001549
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001550
1551 StringPiece method_name(dex_file.GetMethodName(method_id));
1552 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001553 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1554 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001555
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001556 if (method_name == "finalize") {
1557 // Create the prototype for a signature of "()V"
1558 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1559 if (void_string_id != NULL) {
1560 const DexFile::TypeId* void_type_id =
1561 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1562 if (void_type_id != NULL) {
1563 std::vector<uint16_t> no_args;
1564 const DexFile::ProtoId* finalizer_proto =
1565 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1566 if (finalizer_proto != NULL) {
1567 // We have the prototype in the dex file
1568 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1569 klass->SetFinalizable();
1570 } else {
1571 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1572 // The Enum class declares a "final" finalize() method to prevent subclasses from
1573 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1574 // subclasses, so we exclude it here.
1575 // We also want to avoid setting the flag on Object, where we know that finalize() is
1576 // empty.
1577 if (klass_descriptor != "Ljava/lang/Object;" &&
1578 klass_descriptor != "Ljava/lang/Enum;") {
1579 klass->SetFinalizable();
1580 }
1581 }
1582 }
1583 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001584 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001585 }
Ian Rogers0571d352011-11-03 19:51:38 -07001586 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001587 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001588
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001589 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
Ian Rogers19846512012-02-24 11:42:47 -08001590 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001591 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001592 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001593}
1594
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001595void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001596 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1597 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001598}
1599
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001600void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1601 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001602 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001603 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001604}
1605
Brian Carlstromaded5f72011-10-07 17:15:04 -07001606bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001607 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001608 for (size_t i = 0; i != dex_files_.size(); ++i) {
1609 if (dex_files_[i] == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08001610 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001611 }
1612 }
1613 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001614}
1615
Brian Carlstromaded5f72011-10-07 17:15:04 -07001616bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001617 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001618 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001619}
1620
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001621void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001622 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001623 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001624 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001625 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001626 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001627}
1628
Brian Carlstromaded5f72011-10-07 17:15:04 -07001629void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001630 {
1631 MutexLock mu(dex_lock_);
1632 if (IsDexFileRegisteredLocked(dex_file)) {
1633 return;
1634 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001635 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001636 // Don't alloc while holding the lock, since allocation may need to
1637 // suspend all threads and another thread may need the dex_lock_ to
1638 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001639 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001640 {
1641 MutexLock mu(dex_lock_);
1642 if (IsDexFileRegisteredLocked(dex_file)) {
1643 return;
1644 }
1645 RegisterDexFileLocked(dex_file, dex_cache);
1646 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001647}
1648
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001649void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001650 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001651 RegisterDexFileLocked(dex_file, dex_cache);
1652}
1653
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001654const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001655 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001656 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001657 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1658 if (dex_caches_[i] == dex_cache) {
Ian Rogers19846512012-02-24 11:42:47 -08001659 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001660 }
1661 }
Elliott Hughes7b9d9962012-04-20 18:48:18 -07001662 LOG(FATAL) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001663 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001664}
1665
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001666DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001667 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001668 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001669 if (dex_files_[i] == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08001670 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001671 }
1672 }
Elliott Hughes7b9d9962012-04-20 18:48:18 -07001673 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001674 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001675}
1676
Ian Rogers19846512012-02-24 11:42:47 -08001677void ClassLinker::FixupDexCaches(Method* resolution_method) const {
1678 MutexLock mu(dex_lock_);
1679 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1680 dex_caches_[i]->Fixup(resolution_method);
1681 }
1682}
1683
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001684Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1685 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001686 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001687 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001688 CHECK(primitive_class != NULL);
1689 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001690 primitive_class->SetPrimitiveType(type);
1691 primitive_class->SetStatus(Class::kStatusInitialized);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001692 Class* existing = InsertClass(descriptor, primitive_class, false);
1693 CHECK(existing == NULL) << "InitPrimitiveClass(" << descriptor << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001694 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001695}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001696
Brian Carlstrombe977852011-07-19 14:54:54 -07001697// Create an array class (i.e. the class object for the array, not the
1698// array itself). "descriptor" looks like "[C" or "[[[[B" or
1699// "[Ljava/lang/String;".
1700//
1701// If "descriptor" refers to an array of primitives, look up the
1702// primitive type's internally-generated class object.
1703//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001704// "class_loader" is the class loader of the class that's referring to
1705// us. It's used to ensure that we're looking for the element type in
1706// the right context. It does NOT become the class loader for the
1707// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001708//
1709// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001710Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001711 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001712
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001713 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001714 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001715 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001716 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001717 return NULL;
1718 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001719
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001720 // See if the component type is already loaded. Array classes are
1721 // always associated with the class loader of their underlying
1722 // element type -- an array of Strings goes with the loader for
1723 // java/lang/String -- so we need to look for it there. (The
1724 // caller should have checked for the existence of the class
1725 // before calling here, but they did so with *their* class loader,
1726 // not the component type's loader.)
1727 //
1728 // If we find it, the caller adds "loader" to the class' initiating
1729 // loader list, which should prevent us from going through this again.
1730 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001731 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001732 // are the same, because our caller (FindClass) just did the
1733 // lookup. (Even if we get this wrong we still have correct behavior,
1734 // because we effectively do this lookup again when we add the new
1735 // class to the hash table --- necessary because of possible races with
1736 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001737 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001738 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001739 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001740 return new_class;
1741 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001742 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001743
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001744 // Fill out the fields in the Class.
1745 //
1746 // It is possible to execute some methods against arrays, because
1747 // all arrays are subclasses of java_lang_Object_, so we need to set
1748 // up a vtable. We can just point at the one in java_lang_Object_.
1749 //
1750 // Array classes are simple enough that we don't need to do a full
1751 // link step.
1752
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001753 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001754 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001755 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001756 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001757 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001758 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001759 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001760 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001761 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001762 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001763 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001764 }
1765 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001766 if (new_class.get() == NULL) {
1767 new_class.reset(AllocClass(sizeof(Class)));
1768 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001769 return NULL;
1770 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001771 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001772 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001773 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001774 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001775 new_class->SetSuperClass(java_lang_Object);
1776 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001777 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001778 new_class->SetClassLoader(component_type->GetClassLoader());
1779 new_class->SetStatus(Class::kStatusInitialized);
1780 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001781 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001782
1783
1784 // All arrays have java/lang/Cloneable and java/io/Serializable as
1785 // interfaces. We need to set that up here, so that stuff like
1786 // "instanceof" works right.
1787 //
1788 // Note: The GC could run during the call to FindSystemClass,
1789 // so we need to make sure the class object is GC-valid while we're in
1790 // there. Do this by clearing the interface list so the GC will just
1791 // think that the entries are null.
1792
1793
1794 // Use the single, global copies of "interfaces" and "iftable"
1795 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001796 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001797 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001798
1799 // Inherit access flags from the component type. Arrays can't be
1800 // used as a superclass or interface, so we want to add "final"
1801 // and remove "interface".
1802 //
1803 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001804 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001805 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001806 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1807 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001808
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001809 Class* existing = InsertClass(descriptor, new_class.get(), false);
1810 if (existing == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001811 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001812 }
1813 // Another thread must have loaded the class after we
1814 // started but before we finished. Abandon what we've
1815 // done.
1816 //
1817 // (Yes, this happens.)
1818
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001819 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001820}
1821
1822Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001823 switch (Primitive::GetType(type)) {
1824 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001825 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001826 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001827 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001828 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001829 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001830 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001831 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001832 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001833 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001834 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001835 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001836 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001837 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001838 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001839 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001840 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001841 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001842 case Primitive::kPrimNot:
1843 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001844 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001845 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001846 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001847 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001848}
1849
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001850Class* ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001851 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001852 DexCache* dex_cache = klass->GetDexCache();
1853 std::string source;
1854 if (dex_cache != NULL) {
1855 source += " from ";
1856 source += dex_cache->GetLocation()->ToModifiedUtf8();
1857 }
1858 LOG(INFO) << "Loaded class " << descriptor << source;
1859 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001860 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001861 MutexLock mu(classes_lock_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001862 Table& classes = image_class ? image_classes_ : classes_;
Elliott Hughesf8349362012-06-18 15:00:06 -07001863 Class* existing = LookupClassLocked(descriptor.data(), klass->GetClassLoader(), hash, classes);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001864#ifndef NDEBUG
1865 // Check we don't have the class in the other table in error
1866 Table& other_classes = image_class ? classes_ : image_classes_;
Elliott Hughesf8349362012-06-18 15:00:06 -07001867 CHECK(LookupClassLocked(descriptor.data(), klass->GetClassLoader(), hash, other_classes) == NULL);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001868#endif
1869 if (existing != NULL) {
1870 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07001871 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001872 classes.insert(std::make_pair(hash, klass));
1873 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001874}
1875
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001876bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1877 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001878 MutexLock mu(classes_lock_);
Elliott Hughese5448b52012-01-18 16:44:06 -08001879 typedef Table::iterator It; // TODO: C++0x auto
Brian Carlstromae826982011-11-09 01:33:42 -08001880 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001881 ClassHelper kh;
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001882 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001883 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001884 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001885 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001886 classes_.erase(it);
1887 return true;
1888 }
1889 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001890 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001891 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001892 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001893 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001894 image_classes_.erase(it);
1895 return true;
1896 }
1897 }
1898 return false;
1899}
1900
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001901Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1902 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001903 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001904 // TODO: determine if its better to search classes_ or image_classes_ first
Elliott Hughesf8349362012-06-18 15:00:06 -07001905 Class* klass = LookupClassLocked(descriptor, class_loader, hash, classes_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001906 if (klass != NULL) {
1907 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001908 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001909 return LookupClassLocked(descriptor, class_loader, hash, image_classes_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001910}
1911
Elliott Hughesf8349362012-06-18 15:00:06 -07001912Class* ClassLinker::LookupClassLocked(const char* descriptor, const ClassLoader* class_loader,
1913 size_t hash, const Table& classes) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001914 ClassHelper kh(NULL, this);
1915 typedef Table::const_iterator It; // TODO: C++0x auto
1916 for (It it = classes.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001917 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001918 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001919 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001920#ifndef NDEBUG
1921 for (++it; it != end && it->first == hash; ++it) {
Ian Rogersd85016c2012-02-03 18:27:34 -08001922 Class* klass2 = it->second;
1923 kh.ChangeClass(klass2);
1924 CHECK(!(strcmp(descriptor, kh.GetDescriptor()) == 0 && klass2->GetClassLoader() == class_loader))
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001925 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
Ian Rogersd85016c2012-02-03 18:27:34 -08001926 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001927 }
1928#endif
Ian Rogers5d76c432011-10-31 21:42:49 -07001929 return klass;
1930 }
1931 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001932 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001933}
1934
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001935void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001936 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001937 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001938 MutexLock mu(classes_lock_);
1939 typedef Table::const_iterator It; // TODO: C++0x auto
1940 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001941 ClassHelper kh(NULL, this);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001942 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001943 Class* klass = it->second;
1944 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001945 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001946 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001947 }
1948 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001949 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001950 Class* klass = it->second;
1951 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001952 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001953 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001954 }
1955 }
1956}
1957
TDYa1273db52852012-04-01 15:11:43 -07001958#if !defined(NDEBUG) && !defined(ART_USE_LLVM_COMPILER)
Ian Rogersc20a83e2012-01-18 18:15:32 -08001959static void CheckMethodsHaveGcMaps(Class* klass) {
1960 if (!Runtime::Current()->IsStarted()) {
1961 return;
1962 }
1963 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
1964 Method* method = klass->GetDirectMethod(i);
1965 if (!method->IsNative() && !method->IsAbstract()) {
1966 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1967 }
1968 }
1969 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
1970 Method* method = klass->GetVirtualMethod(i);
1971 if (!method->IsNative() && !method->IsAbstract()) {
1972 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1973 }
1974 }
1975}
1976#else
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001977static void CheckMethodsHaveGcMaps(Class*) {
Ian Rogersc20a83e2012-01-18 18:15:32 -08001978}
1979#endif
1980
jeffhao98eacac2011-09-14 16:11:53 -07001981void ClassLinker::VerifyClass(Class* klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08001982 // TODO: assert that the monitor on the Class is held
Elliott Hughesd9c67be2012-02-02 19:54:06 -08001983 ObjectLock lock(klass);
1984
jeffhao98eacac2011-09-14 16:11:53 -07001985 if (klass->IsVerified()) {
1986 return;
1987 }
1988
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08001989 // The class might already be erroneous if we attempted to verify a subclass
1990 if (klass->IsErroneous()) {
1991 ThrowEarlierClassFailure(klass);
1992 return;
1993 }
1994
jeffhaoa9b3bf42012-06-06 17:18:39 -07001995 CHECK(klass->GetStatus() == Class::kStatusResolved ||
1996 klass->GetStatus() == Class::kStatusRetryVerificationAtRuntime) << PrettyClass(klass);
jeffhao98eacac2011-09-14 16:11:53 -07001997 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001998
Ian Rogers1c5eb702012-02-01 09:18:34 -08001999 // Verify super class
2000 Class* super = klass->GetSuperClass();
2001 std::string error_msg;
2002 if (super != NULL) {
2003 // Acquire lock to prevent races on verifying the super class
2004 ObjectLock lock(super);
2005
2006 if (!super->IsVerified() && !super->IsErroneous()) {
2007 Runtime::Current()->GetClassLinker()->VerifyClass(super);
2008 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002009 if (!super->IsCompileTimeVerified()) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08002010 error_msg = "Rejecting class ";
2011 error_msg += PrettyDescriptor(klass);
2012 error_msg += " that attempts to sub-class erroneous class ";
2013 error_msg += PrettyDescriptor(super);
2014 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
2015 Thread* self = Thread::Current();
2016 SirtRef<Throwable> cause(self->GetException());
2017 if (cause.get() != NULL) {
2018 self->ClearException();
2019 }
2020 self->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
2021 if (cause.get() != NULL) {
2022 self->GetException()->SetCause(cause.get());
2023 }
2024 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyDescriptor(klass);
2025 klass->SetStatus(Class::kStatusError);
2026 return;
2027 }
2028 }
2029
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002030 // Try to use verification information from the oat file, otherwise do runtime verification.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002031 const DexFile& dex_file = FindDexFile(klass->GetDexCache());
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002032 Class::Status oat_file_class_status(Class::kStatusNotReady);
2033 bool preverified = VerifyClassUsingOatFile(dex_file, klass, oat_file_class_status);
jeffhaof1e6b7c2012-06-05 18:33:30 -07002034 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
2035 if (!preverified) {
2036 verifier_failure = verifier::MethodVerifier::VerifyClass(klass, error_msg);
2037 }
2038 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002039 if (!preverified && oat_file_class_status == Class::kStatusError) {
2040 LOG(FATAL) << "Verification failed hard on class " << PrettyDescriptor(klass)
2041 << " at compile time, but succeeded at runtime! The verifier must be broken.";
2042 }
Ian Rogersc4762272012-02-01 15:55:55 -08002043 DCHECK(!Thread::Current()->IsExceptionPending());
jeffhaof1e6b7c2012-06-05 18:33:30 -07002044 CHECK(verifier_failure == verifier::MethodVerifier::kNoFailure ||
2045 Runtime::Current()->IsCompiler());
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002046 // Make sure all classes referenced by catch blocks are resolved
2047 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaof1e6b7c2012-06-05 18:33:30 -07002048 klass->SetStatus(verifier_failure == verifier::MethodVerifier::kNoFailure ?
2049 Class::kStatusVerified : Class::kStatusRetryVerificationAtRuntime);
Ian Rogersc20a83e2012-01-18 18:15:32 -08002050 // Sanity check that a verified class has GC maps on all methods
2051 CheckMethodsHaveGcMaps(klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07002052 } else {
Ian Rogers09f6b562012-01-31 21:58:52 -08002053 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass)
Ian Rogers1c5eb702012-02-01 09:18:34 -08002054 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2055 << " because: " << error_msg;
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002056 Thread* self = Thread::Current();
Ian Rogersc4762272012-02-01 15:55:55 -08002057 CHECK(!self->IsExceptionPending());
Ian Rogers1c5eb702012-02-01 09:18:34 -08002058 self->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
2059 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyDescriptor(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002060 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07002061 }
jeffhao98eacac2011-09-14 16:11:53 -07002062}
2063
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002064bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, Class* klass,
2065 Class::Status& oat_file_class_status) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002066 if (!Runtime::Current()->IsStarted()) {
2067 return false;
2068 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002069 if (Runtime::Current()->UseCompileTimeClassPath()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002070 return false;
2071 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002072 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
2073 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002074 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002075 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002076 const char* descriptor = ClassHelper(klass).GetDescriptor();
2077 uint32_t class_def_index;
2078 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002079 CHECK(found) << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002080 UniquePtr<const OatFile::OatClass> oat_class(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002081 CHECK(oat_class.get() != NULL)
2082 << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002083 oat_file_class_status = oat_class->GetStatus();
2084 if (oat_file_class_status == Class::kStatusVerified || oat_file_class_status == Class::kStatusInitialized) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002085 return true;
2086 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002087 if (oat_file_class_status == Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07002088 // Compile time verification failed with a soft error. Compile time verification can fail
2089 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08002090 // class ... {
2091 // Foo x;
2092 // .... () {
2093 // if (...) {
2094 // v1 gets assigned a type of resolved class Foo
2095 // } else {
2096 // v1 gets assigned a type of unresolved class Bar
2097 // }
2098 // iput x = v1
2099 // } }
2100 // when we merge v1 following the if-the-else it results in Conflict
2101 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
2102 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
2103 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
2104 // at compile time).
2105 return false;
2106 }
jeffhao1ac29442012-03-26 11:37:32 -07002107 if (oat_file_class_status == Class::kStatusError) {
2108 // Compile time verification failed with a hard error. This is caused by invalid instructions
2109 // in the class. These errors are unrecoverable.
2110 return false;
2111 }
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002112 if (oat_file_class_status == Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08002113 // Status is uninitialized if we couldn't determine the status at compile time, for example,
2114 // not loading the class.
2115 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
2116 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002117 return false;
2118 }
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002119 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002120 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
2121
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002122 return false;
2123}
2124
2125void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, Class* klass) {
2126 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
2127 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
2128 }
2129 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
2130 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
2131 }
2132}
2133
2134void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, Method* method) {
2135 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
2136 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
2137 if (code_item == NULL) {
2138 return; // native or abstract method
2139 }
2140 if (code_item->tries_size_ == 0) {
2141 return; // nothing to process
2142 }
2143 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
2144 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2145 ClassLinker* linker = Runtime::Current()->GetClassLinker();
2146 for (uint32_t idx = 0; idx < handlers_size; idx++) {
2147 CatchHandlerIterator iterator(handlers_ptr);
2148 for (; iterator.HasNext(); iterator.Next()) {
2149 // Ensure exception types are resolved so that they don't need resolution to be delivered,
2150 // unresolved exception types will be ignored by exception delivery
2151 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
2152 Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
2153 if (exception_type == NULL) {
2154 DCHECK(Thread::Current()->IsExceptionPending());
2155 Thread::Current()->ClearException();
2156 }
2157 }
2158 }
2159 handlers_ptr = iterator.EndDataPointer();
2160 }
2161}
2162
Ian Rogersc2b44472011-12-14 21:17:17 -08002163static void CheckProxyConstructor(Method* constructor);
2164static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
2165
Jesse Wilson95caa792011-10-12 18:14:17 -04002166Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002167 ClassLoader* loader, ObjectArray<Method>* methods,
2168 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08002169 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002170 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08002171 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04002172 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002173 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002174 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002175 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002176 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07002177 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002178 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08002179
2180 klass->SetStatus(Class::kStatusIdx);
2181
2182 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
2183
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002184 // Instance fields are inherited, but we add a couple of static fields...
2185 klass->SetSFields(AllocObjectArray<Field>(2));
2186 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
2187 // our proxy, so Class.getInterfaces doesn't return the flattened set.
2188 SirtRef<Field> interfaces_sfield(AllocField());
2189 klass->SetStaticField(0, interfaces_sfield.get());
2190 interfaces_sfield->SetDexFieldIndex(0);
2191 interfaces_sfield->SetDeclaringClass(klass.get());
2192 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
2193 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
2194 SirtRef<Field> throws_sfield(AllocField());
2195 klass->SetStaticField(1, throws_sfield.get());
2196 throws_sfield->SetDexFieldIndex(1);
2197 throws_sfield->SetDeclaringClass(klass.get());
2198 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002199
Ian Rogers466bb252011-10-14 03:29:56 -07002200 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04002201 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002202 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04002203
Ian Rogers466bb252011-10-14 03:29:56 -07002204 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04002205 size_t num_virtual_methods = methods->GetLength();
2206 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
2207 for (size_t i = 0; i < num_virtual_methods; ++i) {
TDYa127f4404052012-04-11 08:53:03 -07002208#if defined(ART_USE_LLVM_COMPILER)
2209 Method* method = methods->Get(i);
2210 // Ensure link.
2211 // TODO: Remove this after fixing the link problem by in-place linking.
2212 if (method->GetCode() == NULL || method->GetInvokeStub() == NULL) {
2213 Runtime::Current()->GetClassLinker()->LinkOatCodeFor(methods->Get(i));
2214 }
2215#endif
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002216 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002217 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04002218 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002219
2220 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
2221 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
2222 DCHECK(!Thread::Current()->IsExceptionPending());
2223
2224 // Link the fields and virtual methods, creating vtable and iftables
2225 if (!LinkClass(klass, interfaces)) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002226 klass->SetStatus(Class::kStatusError);
Jesse Wilson95caa792011-10-12 18:14:17 -04002227 return NULL;
2228 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002229 interfaces_sfield->SetObject(NULL, interfaces);
2230 throws_sfield->SetObject(NULL, throws);
Ian Rogersc2b44472011-12-14 21:17:17 -08002231 klass->SetStatus(Class::kStatusInitialized);
2232
2233 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07002234 if (kIsDebugBuild) {
Ian Rogersc2b44472011-12-14 21:17:17 -08002235 CHECK(klass->GetIFields() == NULL);
2236 CheckProxyConstructor(klass->GetDirectMethod(0));
2237 for (size_t i = 0; i < num_virtual_methods; ++i) {
2238 SirtRef<Method> prototype(methods->Get(i));
2239 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
2240 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002241
2242 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
2243 name->ToModifiedUtf8().c_str()));
2244 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
2245
2246 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
2247 name->ToModifiedUtf8().c_str()));
2248 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08002249
2250 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002251 CHECK_EQ(synth_proxy_class->GetInterfaces(), interfaces);
Ian Rogersc2b44472011-12-14 21:17:17 -08002252 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
2253 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002254 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04002255}
2256
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002257std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
2258 DCHECK(proxy_class->IsProxyClass());
2259 String* name = proxy_class->GetName();
2260 DCHECK(name != NULL);
2261 return DotToDescriptor(name->ToModifiedUtf8().c_str());
2262}
2263
Ian Rogers16f93672012-02-14 12:29:06 -08002264Method* ClassLinker::FindMethodForProxy(const Class* proxy_class, const Method* proxy_method) {
2265 DCHECK(proxy_class->IsProxyClass());
2266 DCHECK(proxy_method->IsProxyMethod());
2267 // Locate the dex cache of the original interface/Object
2268 DexCache* dex_cache = NULL;
2269 {
2270 ObjectArray<Class>* resolved_types = proxy_method->GetDexCacheResolvedTypes();
2271 MutexLock mu(dex_lock_);
2272 for (size_t i = 0; i != dex_caches_.size(); ++i) {
2273 if (dex_caches_[i]->GetResolvedTypes() == resolved_types) {
2274 dex_cache = dex_caches_[i];
2275 break;
2276 }
2277 }
2278 }
2279 CHECK(dex_cache != NULL);
2280 uint32_t method_idx = proxy_method->GetDexMethodIndex();
2281 Method* resolved_method = dex_cache->GetResolvedMethod(method_idx);
2282 CHECK(resolved_method != NULL);
2283 return resolved_method;
2284}
2285
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002286
2287Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07002288 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07002289 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04002290 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07002291 Method* proxy_constructor = proxy_direct_methods->Get(2);
TDYa1275bb86012012-04-11 05:57:28 -07002292#if defined(ART_USE_LLVM_COMPILER)
2293 // Ensure link.
2294 // TODO: Remove this after fixing the link problem by in-place linking.
2295 art_fix_stub_from_code(proxy_constructor);
2296#endif
Ian Rogers466bb252011-10-14 03:29:56 -07002297 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
2298 // code_ too)
2299 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
2300 // Make this constructor public and fix the class to be our Proxy version
2301 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002302 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08002303 return constructor;
2304}
2305
2306static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07002307 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002308 MethodHelper mh(constructor);
2309 CHECK_STREQ(mh.GetName(), "<init>");
Elliott Hughesba8eee12012-01-24 20:25:24 -08002310 CHECK_EQ(mh.GetSignature(), std::string("(Ljava/lang/reflect/InvocationHandler;)V"));
Ian Rogers466bb252011-10-14 03:29:56 -07002311 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04002312}
2313
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002314Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
2315 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
2316 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08002317 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
2318 prototype.get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002319 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07002320 // as necessary
2321 Method* method = down_cast<Method*>(prototype->Clone());
2322
2323 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
2324 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002325 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07002326 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002327
Ian Rogers466bb252011-10-14 03:29:56 -07002328 // At runtime the method looks like a reference and argument saving method, clone the code
2329 // related parameters from this method.
2330 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
2331 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
2332 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
2333 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
TDYa1275bb86012012-04-11 05:57:28 -07002334#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers466bb252011-10-14 03:29:56 -07002335 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
TDYa1275bb86012012-04-11 05:57:28 -07002336#else
Logan Chien7a2a23a2012-06-06 11:01:00 +08002337 OatFile::OatMethod oat_method = GetOatMethodFor(prototype.get());
2338 method->SetCode(oat_method.GetProxyStub());
TDYa1275bb86012012-04-11 05:57:28 -07002339#endif
Ian Rogers16f93672012-02-14 12:29:06 -08002340
Ian Rogersc2b44472011-12-14 21:17:17 -08002341 return method;
2342}
Jesse Wilson95caa792011-10-12 18:14:17 -04002343
Ian Rogersc2b44472011-12-14 21:17:17 -08002344static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07002345 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002346 CHECK(!prototype->IsFinal());
2347 CHECK(method->IsFinal());
2348 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08002349
2350 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
2351 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
2352 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
2353 CHECK_EQ(prototype->GetDexCacheResolvedMethods(), method->GetDexCacheResolvedMethods());
2354 CHECK_EQ(prototype->GetDexCacheResolvedTypes(), method->GetDexCacheResolvedTypes());
2355 CHECK_EQ(prototype->GetDexCacheInitializedStaticStorage(),
2356 method->GetDexCacheInitializedStaticStorage());
2357 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
2358
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002359 MethodHelper mh(method);
Ian Rogers19846512012-02-24 11:42:47 -08002360 MethodHelper mh2(prototype.get());
2361 CHECK_STREQ(mh.GetName(), mh2.GetName());
2362 CHECK_STREQ(mh.GetShorty(), mh2.GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07002363 // More complex sanity - via dex cache
Ian Rogers19846512012-02-24 11:42:47 -08002364 CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04002365}
2366
Ian Rogers0045a292012-03-31 21:08:41 -07002367bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit, bool can_init_statics) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002368 CHECK(klass->IsResolved() || klass->IsErroneous())
2369 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002370
Carl Shapirob5573532011-07-12 18:22:59 -07002371 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002372
Brian Carlstrom25c33252011-09-18 15:58:35 -07002373 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002374 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002375 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002376 ObjectLock lock(klass);
2377
Brian Carlstromd1422f82011-09-28 11:37:09 -07002378 if (klass->GetStatus() == Class::kStatusInitialized) {
2379 return true;
2380 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002381
Brian Carlstromd1422f82011-09-28 11:37:09 -07002382 if (klass->IsErroneous()) {
2383 ThrowEarlierClassFailure(klass);
2384 return false;
2385 }
2386
jeffhaoebe2e0f2012-06-06 15:19:40 -07002387 if (klass->GetStatus() == Class::kStatusResolved ||
2388 klass->GetStatus() == Class::kStatusRetryVerificationAtRuntime) {
jeffhao98eacac2011-09-14 16:11:53 -07002389 VerifyClass(klass);
2390 if (klass->GetStatus() != Class::kStatusVerified) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07002391 if (klass->GetStatus() == Class::kStatusError) {
2392 CHECK(self->IsExceptionPending());
2393 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002394 return false;
2395 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002396 }
2397
Brian Carlstrom25c33252011-09-18 15:58:35 -07002398 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
2399 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002400 // if the class has a <clinit> but we can't run it during compilation,
Ian Rogers1bddec32012-02-04 12:27:34 -08002401 // don't bother going to kStatusInitializing. We return false so that
2402 // sub-classes don't believe this class is initialized.
Ian Rogers19846512012-02-24 11:42:47 -08002403 // Opportunistically link non-static methods, TODO: don't initialize and dirty pages
2404 // in second pass.
Ian Rogers1bddec32012-02-04 12:27:34 -08002405 return false;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002406 }
2407
Brian Carlstromd1422f82011-09-28 11:37:09 -07002408 // If the class is kStatusInitializing, either this thread is
2409 // initializing higher up the stack or another thread has beat us
2410 // to initializing and we need to wait. Either way, this
2411 // invocation of InitializeClass will not be responsible for
2412 // running <clinit> and will return.
2413 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002414 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002415 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002416 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002417 return true;
2418 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002419 // No. That's fine. Wait for another thread to finish initializing.
2420 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002421 }
2422
2423 if (!ValidateSuperClassDescriptors(klass)) {
2424 klass->SetStatus(Class::kStatusError);
2425 return false;
2426 }
2427
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002428 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified) << PrettyClass(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002429
Elliott Hughesdcc24742011-09-07 14:02:44 -07002430 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002431 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002432 }
2433
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002434 uint64_t t0 = NanoTime();
2435
Ian Rogers0045a292012-03-31 21:08:41 -07002436 if (!InitializeSuperClass(klass, can_run_clinit, can_init_statics)) {
Ian Rogers1bddec32012-02-04 12:27:34 -08002437 // Super class initialization failed, this can be because we can't run
2438 // super-class class initializers in which case we'll be verified.
2439 // Otherwise this class is erroneous.
2440 if (!can_run_clinit) {
2441 CHECK(klass->IsVerified());
2442 } else {
2443 CHECK(klass->IsErroneous());
2444 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002445 return false;
2446 }
2447
Ian Rogers0045a292012-03-31 21:08:41 -07002448 bool has_static_field_initializers = InitializeStaticFields(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002449
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002450 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002451 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002452 }
2453
Ian Rogers19846512012-02-24 11:42:47 -08002454 FixupStaticTrampolines(klass);
2455
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002456 uint64_t t1 = NanoTime();
2457
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002458 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002459 {
2460 ObjectLock lock(klass);
2461
2462 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002463 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002464 klass->SetStatus(Class::kStatusError);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002465 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002466 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002467 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2468 RuntimeStats* thread_stats = self->GetStats();
2469 ++global_stats->class_init_count;
2470 ++thread_stats->class_init_count;
2471 global_stats->class_init_time_ns += (t1 - t0);
2472 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogers0045a292012-03-31 21:08:41 -07002473 // Set the class as initialized except if we can't initialize static fields and static field
2474 // initialization is necessary.
2475 if (!can_init_statics && has_static_field_initializers) {
2476 klass->SetStatus(Class::kStatusVerified); // Don't leave class in initializing state.
2477 success = false;
2478 } else {
2479 klass->SetStatus(Class::kStatusInitialized);
2480 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002481 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002482 ClassHelper kh(klass);
2483 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002484 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002485 }
2486 lock.NotifyAll();
2487 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002488 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002489}
2490
Brian Carlstromd1422f82011-09-28 11:37:09 -07002491bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
2492 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002493 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002494 lock.Wait();
2495
2496 // When we wake up, repeat the test for init-in-progress. If
2497 // there's an exception pending (only possible if
2498 // "interruptShouldThrow" was set), bail out.
2499 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002500 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002501 klass->SetStatus(Class::kStatusError);
2502 return false;
2503 }
2504 // Spurious wakeup? Go back to waiting.
2505 if (klass->GetStatus() == Class::kStatusInitializing) {
2506 continue;
2507 }
2508 if (klass->IsErroneous()) {
2509 // The caller wants an exception, but it was thrown in a
2510 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002511 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002512 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002513 return false;
2514 }
2515 if (klass->IsInitialized()) {
2516 return true;
2517 }
2518 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2519 }
2520 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2521}
2522
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002523bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2524 if (klass->IsInterface()) {
2525 return true;
2526 }
2527 // begin with the methods local to the superclass
2528 if (klass->HasSuperClass() &&
2529 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2530 const Class* super = klass->GetSuperClass();
Ian Rogers595799e2012-01-11 17:32:51 -08002531 for (int i = super->GetVTable()->GetLength() - 1; i >= 0; --i) {
2532 const Method* method = klass->GetVTable()->Get(i);
2533 if (method != super->GetVTable()->Get(i) &&
2534 !IsSameMethodSignatureInDifferentClassContexts(method, super, klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002535 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2536 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2537 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002538 return false;
2539 }
2540 }
2541 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002542 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2543 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2544 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002545 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2546 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002547 const Method* method = interface_entry->GetMethodArray()->Get(j);
Ian Rogers595799e2012-01-11 17:32:51 -08002548 if (!IsSameMethodSignatureInDifferentClassContexts(method, interface,
2549 method->GetDeclaringClass())) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002550 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2551 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2552 PrettyMethod(method).c_str(),
2553 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002554 return false;
2555 }
2556 }
2557 }
2558 }
2559 return true;
2560}
2561
Ian Rogers595799e2012-01-11 17:32:51 -08002562// Returns true if classes referenced by the signature of the method are the
2563// same classes in klass1 as they are in klass2.
2564bool ClassLinker::IsSameMethodSignatureInDifferentClassContexts(const Method* method,
2565 const Class* klass1,
2566 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002567 if (klass1 == klass2) {
2568 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002569 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002570 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002571 const DexFile::ProtoId& proto_id =
2572 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002573 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2574 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002575 if (descriptor == NULL) {
2576 break;
2577 }
2578 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2579 // Found a non-primitive type.
Ian Rogers595799e2012-01-11 17:32:51 -08002580 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002581 return false;
2582 }
2583 }
2584 }
2585 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002586 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002587 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Ian Rogers595799e2012-01-11 17:32:51 -08002588 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002589 return false;
2590 }
2591 }
2592 return true;
2593}
2594
Ian Rogers595799e2012-01-11 17:32:51 -08002595// Returns true if the descriptor resolves to the same class in the context of klass1 and klass2.
2596bool ClassLinker::IsSameDescriptorInDifferentClassContexts(const char* descriptor,
2597 const Class* klass1,
2598 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002599 CHECK(descriptor != NULL);
2600 CHECK(klass1 != NULL);
2601 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002602 if (klass1 == klass2) {
2603 return true;
2604 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002605 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Ian Rogers595799e2012-01-11 17:32:51 -08002606 if (found1 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002607 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002608 }
Ian Rogers595799e2012-01-11 17:32:51 -08002609 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
2610 if (found2 == NULL) {
2611 Thread::Current()->ClearException();
2612 }
2613 return found1 == found2;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002614}
2615
Ian Rogers0045a292012-03-31 21:08:41 -07002616bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit, bool can_init_fields) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002617 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002618 if (!klass->IsInterface() && klass->HasSuperClass()) {
2619 Class* super_class = klass->GetSuperClass();
2620 if (super_class->GetStatus() != Class::kStatusInitialized) {
2621 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002622 Thread* self = Thread::Current();
2623 klass->MonitorEnter(self);
Ian Rogers0045a292012-03-31 21:08:41 -07002624 bool super_initialized = InitializeClass(super_class, can_run_clinit, can_init_fields);
Elliott Hughes5f791332011-09-15 17:45:30 -07002625 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002626 // TODO: check for a pending exception
2627 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002628 if (!can_run_clinit) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002629 // Don't set status to error when we can't run <clinit>.
2630 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing) << PrettyClass(klass);
2631 klass->SetStatus(Class::kStatusVerified);
2632 return false;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002633 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002634 klass->SetStatus(Class::kStatusError);
2635 klass->NotifyAll();
2636 return false;
2637 }
2638 }
2639 }
2640 return true;
2641}
2642
Ian Rogers0045a292012-03-31 21:08:41 -07002643bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit, bool can_init_fields) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002644 CHECK(c != NULL);
2645 if (c->IsInitialized()) {
2646 return true;
2647 }
2648
Elliott Hughes5f791332011-09-15 17:45:30 -07002649 Thread* self = Thread::Current();
Elliott Hughes34e06962012-04-09 13:55:55 -07002650 ScopedThreadStateChange tsc(self, kRunnable);
Ian Rogers0045a292012-03-31 21:08:41 -07002651 bool success = InitializeClass(c, can_run_clinit, can_init_fields);
Ian Rogers595799e2012-01-11 17:32:51 -08002652 if (!success) {
Ian Rogers1bddec32012-02-04 12:27:34 -08002653 CHECK(self->IsExceptionPending() || !can_run_clinit) << PrettyClass(c);
Ian Rogers595799e2012-01-11 17:32:51 -08002654 }
2655 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002656}
2657
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002658void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Elliott Hughesa0e18062012-04-13 15:59:59 -07002659 Class* c, SafeMap<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002660 const ClassLoader* cl = c->GetClassLoader();
2661 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002662 ClassDataItemIterator it(dex_file, class_data);
2663 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002664 field_map.Put(i, ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true));
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002665 }
2666}
2667
Ian Rogers0045a292012-03-31 21:08:41 -07002668bool ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002669 size_t num_static_fields = klass->NumStaticFields();
2670 if (num_static_fields == 0) {
Ian Rogers0045a292012-03-31 21:08:41 -07002671 return false;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002672 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002673 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002674 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002675 if (dex_cache == NULL) {
Ian Rogers0045a292012-03-31 21:08:41 -07002676 return false;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002677 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002678 ClassHelper kh(klass);
2679 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002680 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002681 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002682 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002683
Ian Rogers0571d352011-11-03 19:51:38 -07002684 if (it.HasNext()) {
2685 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
Elliott Hughesa0e18062012-04-13 15:59:59 -07002686 SafeMap<uint32_t, Field*> field_map;
Ian Rogers0571d352011-11-03 19:51:38 -07002687 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2688 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002689 it.ReadValueToField(field_map.Get(i));
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002690 }
Ian Rogers0045a292012-03-31 21:08:41 -07002691 return true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002692 }
Ian Rogers0045a292012-03-31 21:08:41 -07002693 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002694}
2695
Ian Rogersc2b44472011-12-14 21:17:17 -08002696bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002697 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002698 if (!LinkSuperClass(klass)) {
2699 return false;
2700 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002701 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002702 return false;
2703 }
2704 if (!LinkInstanceFields(klass)) {
2705 return false;
2706 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002707 if (!LinkStaticFields(klass)) {
2708 return false;
2709 }
2710 CreateReferenceInstanceOffsets(klass);
2711 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002712 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2713 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002714 return true;
2715}
2716
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002717bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002718 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002719 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2720 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
Ian Rogerscab01012012-01-10 17:35:46 -08002721 CHECK(class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002722 uint16_t super_class_idx = class_def->superclass_idx_;
2723 if (super_class_idx != DexFile::kDexNoIndex16) {
2724 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002725 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002726 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002727 return false;
2728 }
Ian Rogersbe125a92012-01-11 15:19:49 -08002729 // Verify
2730 if (!klass->CanAccess(super_class)) {
2731 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2732 "Class %s extended by class %s is inaccessible",
2733 PrettyDescriptor(super_class).c_str(),
2734 PrettyDescriptor(klass.get()).c_str());
2735 return false;
2736 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002737 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002738 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002739 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2740 if (interfaces != NULL) {
2741 for (size_t i = 0; i < interfaces->Size(); i++) {
2742 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2743 Class* interface = ResolveType(dex_file, idx, klass.get());
2744 if (interface == NULL) {
2745 DCHECK(Thread::Current()->IsExceptionPending());
2746 return false;
2747 }
2748 // Verify
2749 if (!klass->CanAccess(interface)) {
2750 // TODO: the RI seemed to ignore this in my testing.
2751 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2752 "Interface %s implemented by class %s is inaccessible",
2753 PrettyDescriptor(interface).c_str(),
2754 PrettyDescriptor(klass.get()).c_str());
2755 return false;
2756 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002757 }
2758 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002759 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002760 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002761 return true;
2762}
2763
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002764bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002765 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002766 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002767 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002768 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002769 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002770 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002771 return false;
2772 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002773 return true;
2774 }
2775 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002776 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002777 return false;
2778 }
2779 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002780 if (super->IsFinal() || super->IsInterface()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002781 Thread* self = Thread::Current();
2782 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002783 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002784 PrettyDescriptor(super).c_str(),
2785 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002786 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002787 return false;
2788 }
2789 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002790 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002791 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002792 PrettyDescriptor(super).c_str(),
2793 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002794 return false;
2795 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002796
2797 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2798 if (super->IsFinalizable()) {
2799 klass->SetFinalizable();
2800 }
2801
Elliott Hughes2da50362011-10-10 16:57:08 -07002802 // Inherit reference flags (if any) from the superclass.
2803 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2804 if (reference_flags != 0) {
2805 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2806 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002807 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002808 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002809 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002810 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002811 return false;
2812 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002813
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002814#ifndef NDEBUG
2815 // Ensure super classes are fully resolved prior to resolving fields..
2816 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002817 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002818 super = super->GetSuperClass();
2819 }
2820#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002821 return true;
2822}
2823
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002824// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002825bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002826 if (klass->IsInterface()) {
2827 // No vtable.
2828 size_t count = klass->NumVirtualMethods();
2829 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002830 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002831 return false;
2832 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002833 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002834 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002835 }
jeffhaobdb76512011-09-07 11:43:16 -07002836 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002837 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002838 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002839 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002840 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002841 }
2842 return true;
2843}
2844
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002845bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002846 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002847 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2848 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002849 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002850 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002851 SirtRef<ObjectArray<Method> > vtable(klass->GetSuperClass()->GetVTable()->CopyOf(max_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002852 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002853 MethodHelper local_mh(NULL, this);
2854 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002855 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002856 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002857 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002858 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002859 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002860 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002861 super_mh.ChangeMethod(super_method);
2862 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002863 // Verify
2864 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002865 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002866 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002867 PrettyDescriptor(klass.get()).c_str(),
2868 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002869 return false;
2870 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002871 vtable->Set(j, local_method);
2872 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002873 break;
2874 }
2875 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002876 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002877 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002878 vtable->Set(actual_count, local_method);
2879 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002880 actual_count += 1;
2881 }
2882 }
2883 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002884 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002885 return false;
2886 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002887 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002888 CHECK_LE(actual_count, max_count);
2889 if (actual_count < max_count) {
Ian Rogers30fab402012-01-23 15:43:46 -08002890 vtable.reset(vtable->CopyOf(actual_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002891 }
Ian Rogers30fab402012-01-23 15:43:46 -08002892 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002893 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002894 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002895 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002896 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002897 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002898 return false;
2899 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002900 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002901 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002902 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2903 vtable->Set(i, virtual_method);
2904 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002905 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002906 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002907 }
2908 return true;
2909}
2910
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002911bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002912 size_t super_ifcount;
2913 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002914 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002915 } else {
2916 super_ifcount = 0;
2917 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002918 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002919 ClassHelper kh(klass.get(), this);
Ian Rogersd24e2642012-06-06 21:21:43 -07002920 uint32_t num_interfaces = interfaces == NULL ? kh.NumDirectInterfaces() : interfaces->GetLength();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002921 ifcount += num_interfaces;
2922 for (size_t i = 0; i < num_interfaces; i++) {
Ian Rogersd24e2642012-06-06 21:21:43 -07002923 Class* interface = interfaces == NULL ? kh.GetDirectInterface(i) : interfaces->Get(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002924 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002925 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002926 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002927 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002928 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002929 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002930 return true;
2931 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002932 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002933 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002934 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2935 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogersb52b01a2012-01-12 17:01:38 -08002936 Class* super_interface = super_iftable->Get(i)->GetInterface();
2937 iftable->Set(i, AllocInterfaceEntry(super_interface));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002938 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002939 }
2940 // Flatten the interface inheritance hierarchy.
2941 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002942 for (size_t i = 0; i < num_interfaces; i++) {
Ian Rogersd24e2642012-06-06 21:21:43 -07002943 Class* interface = interfaces == NULL ? kh.GetDirectInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002944 DCHECK(interface != NULL);
2945 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002946 ClassHelper ih(interface);
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002947 Thread* self = Thread::Current();
2948 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002949 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002950 PrettyDescriptor(klass.get()).c_str(),
2951 PrettyDescriptor(ih.GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002952 return false;
2953 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002954 // Check if interface is already in iftable
2955 bool duplicate = false;
2956 for (size_t j = 0; j < idx; j++) {
2957 Class* existing_interface = iftable->Get(j)->GetInterface();
2958 if (existing_interface == interface) {
2959 duplicate = true;
2960 break;
2961 }
2962 }
2963 if (!duplicate) {
2964 // Add this non-duplicate interface.
2965 iftable->Set(idx++, AllocInterfaceEntry(interface));
2966 // Add this interface's non-duplicate super-interfaces.
2967 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2968 Class* super_interface = interface->GetIfTable()->Get(j)->GetInterface();
2969 bool super_duplicate = false;
2970 for (size_t k = 0; k < idx; k++) {
2971 Class* existing_interface = iftable->Get(k)->GetInterface();
2972 if (existing_interface == super_interface) {
2973 super_duplicate = true;
2974 break;
2975 }
2976 }
2977 if (!super_duplicate) {
2978 iftable->Set(idx++, AllocInterfaceEntry(super_interface));
2979 }
2980 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002981 }
2982 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002983 // Shrink iftable in case duplicates were found
2984 if (idx < ifcount) {
2985 iftable.reset(iftable->CopyOf(idx));
2986 ifcount = idx;
2987 } else {
2988 CHECK_EQ(idx, ifcount);
2989 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002990 klass->SetIfTable(iftable.get());
Elliott Hughes4681c802011-09-25 18:04:37 -07002991
2992 // If we're an interface, we don't need the vtable pointers, so we're done.
2993 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002994 return true;
2995 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002996 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002997 MethodHelper vtable_mh(NULL, this);
2998 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002999 for (size_t i = 0; i < ifcount; ++i) {
3000 InterfaceEntry* interface_entry = iftable->Get(i);
3001 Class* interface = interface_entry->GetInterface();
3002 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
3003 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003004 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003005 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
3006 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003007 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003008 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07003009 // For each method listed in the interface's method list, find the
3010 // matching method in our class's method list. We want to favor the
3011 // subclass over the superclass, which just requires walking
3012 // back from the end of the vtable. (This only matters if the
3013 // superclass defines a private method and this class redefines
3014 // it -- otherwise it would use the same vtable slot. In .dex files
3015 // those don't end up in the virtual method table, so it shouldn't
3016 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003017 for (k = vtable->GetLength() - 1; k >= 0; --k) {
3018 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003019 vtable_mh.ChangeMethod(vtable_method);
3020 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07003021 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07003022 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003023 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003024 return false;
3025 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003026 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003027 break;
3028 }
3029 }
3030 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003031 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07003032 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003033 Method* mir_method = miranda_list[mir];
3034 vtable_mh.ChangeMethod(mir_method);
3035 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003036 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003037 break;
3038 }
3039 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003040 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07003041 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003042 miranda_method.reset(AllocMethod());
3043 memcpy(miranda_method.get(), interface_method, sizeof(Method));
3044 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003045 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003046 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003047 }
3048 }
3049 }
Elliott Hughes4681c802011-09-25 18:04:37 -07003050 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07003051 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07003052 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07003053 klass->SetVirtualMethods((old_method_count == 0)
3054 ? AllocObjectArray<Method>(new_method_count)
3055 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003056
Ian Rogers30fab402012-01-23 15:43:46 -08003057 SirtRef<ObjectArray<Method> > vtable(klass->GetVTableDuringLinking());
3058 CHECK(vtable.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003059 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07003060 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers30fab402012-01-23 15:43:46 -08003061 vtable.reset(vtable->CopyOf(new_vtable_count));
Elliott Hughes4681c802011-09-25 18:04:37 -07003062 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07003063 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07003064 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07003065 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
3066 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
3067 klass->SetVirtualMethod(old_method_count + i, method);
3068 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003069 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003070 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08003071 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003072 }
Elliott Hughes4681c802011-09-25 18:04:37 -07003073
3074 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
3075 for (int i = 0; i < vtable->GetLength(); ++i) {
3076 CHECK(vtable->Get(i) != NULL);
3077 }
3078
3079// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
3080
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003081 return true;
3082}
3083
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003084bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
3085 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003086 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003087}
3088
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003089bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
3090 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003091 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003092 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003093 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07003094 return success;
3095}
3096
Brian Carlstromdbc05252011-09-09 01:59:59 -07003097struct LinkFieldsComparator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08003098 explicit LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07003099 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003100 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003101 fh_->ChangeField(field1);
3102 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
3103 fh_->ChangeField(field2);
3104 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003105 bool isPrimitive1 = type1 != Primitive::kPrimNot;
3106 bool isPrimitive2 = type2 != Primitive::kPrimNot;
3107 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
3108 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003109 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
3110 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
3111 if (order1 != order2) {
3112 return order1 < order2;
3113 }
3114
3115 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003116 fh_->ChangeField(field1);
3117 StringPiece name1(fh_->GetName());
3118 fh_->ChangeField(field2);
3119 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07003120 return name1 < name2;
3121 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003122
3123 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07003124};
3125
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003126bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003127 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003128 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003129
3130 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003131 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003132
3133 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07003134 size_t size;
3135 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003136 if (is_static) {
3137 size = klass->GetClassSize();
3138 field_offset = Class::FieldsOffset();
3139 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003140 Class* super_class = klass->GetSuperClass();
3141 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07003142 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003143 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003144 }
3145 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003146 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003147
Brian Carlstromdbc05252011-09-09 01:59:59 -07003148 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003149
Brian Carlstromdbc05252011-09-09 01:59:59 -07003150 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07003151 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07003152 std::deque<Field*> grouped_and_sorted_fields;
3153 for (size_t i = 0; i < num_fields; i++) {
3154 grouped_and_sorted_fields.push_back(fields->Get(i));
3155 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003156 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003157 std::sort(grouped_and_sorted_fields.begin(),
3158 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003159 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07003160
3161 // References should be at the front.
3162 size_t current_field = 0;
3163 size_t num_reference_fields = 0;
3164 for (; current_field < num_fields; current_field++) {
3165 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003166 fh.ChangeField(field);
3167 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003168 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07003169 if (isPrimitive) {
3170 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003171 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07003172 grouped_and_sorted_fields.pop_front();
3173 num_reference_fields++;
3174 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003175 field->SetOffset(field_offset);
3176 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003177 }
3178
3179 // Now we want to pack all of the double-wide fields together. If
3180 // we're not aligned, though, we want to shuffle one 32-bit field
3181 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07003182 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003183 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
3184 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003185 fh.ChangeField(field);
3186 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003187 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
3188 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003189 continue;
3190 }
3191 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003192 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003193 // drop the consumed field
3194 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
3195 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003196 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07003197 // whether we found a 32-bit field for padding or not, we advance
3198 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003199 }
3200
3201 // Alignment is good, shuffle any double-wide fields forward, and
3202 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07003203 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07003204 while (!grouped_and_sorted_fields.empty()) {
3205 Field* field = grouped_and_sorted_fields.front();
3206 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003207 fh.ChangeField(field);
3208 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003209 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07003210 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003211 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003212 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003213 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07003214 ? sizeof(uint64_t)
3215 : sizeof(uint32_t)));
3216 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003217 }
3218
Elliott Hughesadb460d2011-10-05 17:02:34 -07003219 // 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 -08003220 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
3221 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07003222 // We know there are no non-reference fields in the Reference classes, and we know
3223 // that 'referent' is alphabetically last, so this is easy...
3224 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003225 fh.ChangeField(fields->Get(num_fields - 1));
Elliott Hughesba8eee12012-01-24 20:25:24 -08003226 CHECK_STREQ(fh.GetName(), "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07003227 --num_reference_fields;
3228 }
3229
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003230#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07003231 // Make sure that all reference fields appear before
3232 // non-reference fields, and all double-wide fields are aligned.
3233 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07003234 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003235 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003236 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003237 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003238 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07003239 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07003240 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
3241 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003242 fh.ChangeField(field);
3243 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003244 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003245 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07003246 is_primitive = true; // We lied above, so we have to expect a lie here.
3247 }
3248 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07003249 if (!seen_non_ref) {
3250 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003251 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003252 }
Brian Carlstrombe977852011-07-19 14:54:54 -07003253 } else {
3254 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003255 }
3256 }
Brian Carlstrombe977852011-07-19 14:54:54 -07003257 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003258 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003259 }
3260#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003261 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003262 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003263 if (is_static) {
3264 klass->SetNumReferenceStaticFields(num_reference_fields);
3265 klass->SetClassSize(size);
3266 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003267 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003268 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003269 klass->SetObjectSize(size);
3270 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003271 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003272 return true;
3273}
3274
3275// Set the bitmap of reference offsets, refOffsets, from the ifields
3276// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003277void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003278 uint32_t reference_offsets = 0;
3279 Class* super_class = klass->GetSuperClass();
3280 if (super_class != NULL) {
3281 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003282 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003283 if (reference_offsets == CLASS_WALK_SUPER) {
3284 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003285 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003286 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003287 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003288 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003289}
3290
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003291void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003292 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003293}
3294
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003295void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003296 uint32_t reference_offsets) {
3297 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003298 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
3299 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003300 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003301 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003302 // All of the fields that contain object references are guaranteed
3303 // to be at the beginning of the fields list.
3304 for (size_t i = 0; i < num_reference_fields; ++i) {
3305 // Note that byte_offset is the offset from the beginning of
3306 // object, not the offset into instance data
3307 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003308 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003309 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
3310 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
3311 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07003312 CHECK_NE(new_bit, 0U);
3313 reference_offsets |= new_bit;
3314 } else {
3315 reference_offsets = CLASS_WALK_SUPER;
3316 break;
3317 }
3318 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003319 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003320 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003321 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003322 } else {
3323 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003324 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003325}
3326
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003327String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07003328 uint32_t string_idx, DexCache* dex_cache) {
Brian Carlstrom7d776242012-03-06 23:05:49 -08003329 DCHECK(dex_cache != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003330 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003331 if (resolved != NULL) {
3332 return resolved;
3333 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003334 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
3335 int32_t utf16_length = dex_file.GetStringLength(string_id);
3336 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07003337 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003338 dex_cache->SetResolvedString(string_idx, string);
3339 return string;
3340}
3341
3342Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003343 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003344 DexCache* dex_cache,
3345 const ClassLoader* class_loader) {
Brian Carlstrom7d776242012-03-06 23:05:49 -08003346 DCHECK(dex_cache != NULL);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003347 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003348 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07003349 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003350 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003351 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05003352 // TODO: we used to throw here if resolved's class loader was not the
3353 // boot class loader. This was to permit different classes with the
3354 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003355 dex_cache->SetResolvedType(type_idx, resolved);
3356 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08003357 CHECK(Thread::Current()->IsExceptionPending())
3358 << "Expected pending exception for failed resolution of: " << descriptor;
jeffhao8cd6dda2012-02-22 10:15:34 -08003359 // Convert a ClassNotFoundException to a NoClassDefFoundError
3360 if (Thread::Current()->GetException()->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
3361 Thread::Current()->ClearException();
3362 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
3363 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003364 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003365 }
3366 return resolved;
3367}
3368
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003369Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
3370 uint32_t method_idx,
3371 DexCache* dex_cache,
3372 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003373 bool is_direct) {
Brian Carlstrom7d776242012-03-06 23:05:49 -08003374 DCHECK(dex_cache != NULL);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003375 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
3376 if (resolved != NULL) {
3377 return resolved;
3378 }
3379 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3380 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
3381 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07003382 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003383 return NULL;
3384 }
3385
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003386 if (is_direct) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003387 resolved = klass->FindDirectMethod(dex_cache, method_idx);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003388 } else if (klass->IsInterface()) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003389 resolved = klass->FindInterfaceMethod(dex_cache, method_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003390 } else {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003391 resolved = klass->FindVirtualMethod(dex_cache, method_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003392 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003393
3394 if (resolved == NULL) {
3395 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
3396 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
3397 if (is_direct) {
3398 resolved = klass->FindDirectMethod(name, signature);
3399 } else if (klass->IsInterface()) {
3400 resolved = klass->FindInterfaceMethod(name, signature);
3401 } else {
3402 resolved = klass->FindVirtualMethod(name, signature);
jeffhao8cd6dda2012-02-22 10:15:34 -08003403 // If a virtual method isn't found, search the direct methods. This can
3404 // happen when trying to access private methods directly, and allows the
3405 // proper exception to be thrown in the caller.
3406 if (resolved == NULL) {
3407 resolved = klass->FindDirectMethod(name, signature);
3408 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003409 }
3410 if (resolved == NULL) {
3411 ThrowNoSuchMethodError(is_direct, klass, name, signature);
3412 return NULL;
3413 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003414 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003415 dex_cache->SetResolvedMethod(method_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003416 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003417}
3418
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003419Field* ClassLinker::ResolveField(const DexFile& dex_file,
3420 uint32_t field_idx,
3421 DexCache* dex_cache,
3422 const ClassLoader* class_loader,
3423 bool is_static) {
Brian Carlstrom7d776242012-03-06 23:05:49 -08003424 DCHECK(dex_cache != NULL);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003425 Field* resolved = dex_cache->GetResolvedField(field_idx);
3426 if (resolved != NULL) {
3427 return resolved;
3428 }
3429 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3430 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3431 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003432 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003433 return NULL;
3434 }
3435
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003436 if (is_static) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003437 resolved = klass->FindStaticField(dex_cache, field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003438 } else {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003439 resolved = klass->FindInstanceField(dex_cache, field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003440 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003441
3442 if (resolved == NULL) {
3443 const char* name = dex_file.GetFieldName(field_id);
3444 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3445 if (is_static) {
3446 resolved = klass->FindStaticField(name, type);
3447 } else {
3448 resolved = klass->FindInstanceField(name, type);
3449 }
3450 if (resolved == NULL) {
3451 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
3452 return NULL;
3453 }
Ian Rogersb067ac22011-12-13 18:05:09 -08003454 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003455 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08003456 return resolved;
3457}
3458
3459Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
3460 uint32_t field_idx,
3461 DexCache* dex_cache,
3462 const ClassLoader* class_loader) {
Brian Carlstrom7d776242012-03-06 23:05:49 -08003463 DCHECK(dex_cache != NULL);
Ian Rogersb067ac22011-12-13 18:05:09 -08003464 Field* resolved = dex_cache->GetResolvedField(field_idx);
3465 if (resolved != NULL) {
3466 return resolved;
3467 }
3468 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3469 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3470 if (klass == NULL) {
3471 DCHECK(Thread::Current()->IsExceptionPending());
3472 return NULL;
3473 }
3474
3475 const char* name = dex_file.GetFieldName(field_id);
3476 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3477 resolved = klass->FindField(name, type);
3478 if (resolved != NULL) {
3479 dex_cache->SetResolvedField(field_idx, resolved);
3480 } else {
3481 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003482 }
3483 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07003484}
3485
Ian Rogers19846512012-02-24 11:42:47 -08003486const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer, uint32_t* length) {
Ian Rogersad25ac52011-10-04 19:13:33 -07003487 Class* declaring_class = referrer->GetDeclaringClass();
3488 DexCache* dex_cache = declaring_class->GetDexCache();
3489 const DexFile& dex_file = FindDexFile(dex_cache);
3490 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08003491 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07003492}
3493
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003494void ClassLinker::DumpAllClasses(int flags) const {
3495 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3496 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3497 std::vector<Class*> all_classes;
3498 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003499 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003500 typedef Table::const_iterator It; // TODO: C++0x auto
3501 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3502 all_classes.push_back(it->second);
3503 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003504 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3505 all_classes.push_back(it->second);
3506 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003507 }
3508
3509 for (size_t i = 0; i < all_classes.size(); ++i) {
3510 all_classes[i]->DumpClass(std::cerr, flags);
3511 }
3512}
3513
Elliott Hughescac6cc72011-11-03 20:31:21 -07003514void ClassLinker::DumpForSigQuit(std::ostream& os) const {
3515 MutexLock mu(classes_lock_);
3516 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3517 << classes_.size() << " allocated classes\n";
3518}
3519
Elliott Hughese27955c2011-08-26 15:21:24 -07003520size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003521 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003522 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003523}
3524
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003525pid_t ClassLinker::GetClassesLockOwner() {
3526 return classes_lock_.GetOwner();
3527}
3528
3529pid_t ClassLinker::GetDexLockOwner() {
3530 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003531}
3532
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003533void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3534 DCHECK(!init_done_);
3535
3536 DCHECK(klass != NULL);
3537 DCHECK(klass->GetClassLoader() == NULL);
3538
3539 DCHECK(class_roots_ != NULL);
3540 DCHECK(class_roots_->Get(class_root) == NULL);
3541 class_roots_->Set(class_root, klass);
3542}
3543
Logan Chien0c717dd2012-03-28 18:31:07 +08003544void ClassLinker::RelocateExecutable() {
Elliott Hughesf8349362012-06-18 15:00:06 -07003545 MutexLock mu(dex_lock_);
Logan Chien0c717dd2012-03-28 18:31:07 +08003546 for (size_t i = 0; i < oat_files_.size(); ++i) {
3547 const_cast<OatFile*>(oat_files_[i])->RelocateExecutable();
3548 }
3549}
3550
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003551} // namespace art