blob: 9ce641febfc39f88d2053471d09480eb2817e8c9 [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"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070049#include "scoped_thread_state_change.h"
Ian Rogers1f539342012-10-03 21:09:42 -070050#include "sirt_ref.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070051#include "space.h"
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070052#include "space_bitmap.h"
Brian Carlstrom40381fb2011-10-19 14:13:40 -070053#include "stack_indirect_reference_table.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070054#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070055#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070056#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070057#include "utils.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070058#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070059
60namespace art {
61
Ian Rogers00f7d0e2012-07-19 15:28:27 -070062static void ThrowNoClassDefFoundError(const char* fmt, ...)
63 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070064 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070065static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070066 va_list args;
67 va_start(args, fmt);
68 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
69 va_end(args);
70}
71
Ian Rogers00f7d0e2012-07-19 15:28:27 -070072static void ThrowClassFormatError(const char* fmt, ...)
73 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070074 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070075static void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070076 va_list args;
77 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070078 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070079 va_end(args);
80}
81
Ian Rogers00f7d0e2012-07-19 15:28:27 -070082static void ThrowLinkageError(const char* fmt, ...)
83 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070084 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070085static void ThrowLinkageError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070086 va_list args;
87 va_start(args, fmt);
88 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
89 va_end(args);
90}
91
Elliott Hughes0512f022012-03-15 22:10:52 -070092static void ThrowNoSuchFieldError(const StringPiece& scope, Class* c, const StringPiece& type,
Ian Rogers00f7d0e2012-07-19 15:28:27 -070093 const StringPiece& name)
Ian Rogersb726dcb2012-09-05 08:57:23 -070094 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers9f1ab122011-12-12 08:52:43 -080095 ClassHelper kh(c);
96 std::ostringstream msg;
Ian Rogers08f753d2012-08-24 14:35:25 -070097 msg << "No " << scope << "field " << name << " of type " << type
Ian Rogers9f1ab122011-12-12 08:52:43 -080098 << " in class " << kh.GetDescriptor() << " or its superclasses";
99 std::string location(kh.GetLocation());
100 if (!location.empty()) {
101 msg << " (defined in " << location << ")";
102 }
103 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchFieldError;", msg.str().c_str());
104}
105
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700106static void ThrowNullPointerException(const char* fmt, ...)
107 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -0700108 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700109static void ThrowNullPointerException(const char* fmt, ...) {
Ian Rogerscab01012012-01-10 17:35:46 -0800110 va_list args;
111 va_start(args, fmt);
112 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NullPointerException;", fmt, args);
113 va_end(args);
114}
115
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700116static void ThrowEarlierClassFailure(Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700117 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
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.
Ian Rogers87e552d2012-08-31 15:54:48 -0700122 if (!Runtime::Current()->IsCompiler()) { // Give info if this occurs at runtime.
123 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
124 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700125
Elliott Hughes5c599942012-06-13 16:45:05 -0700126 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700127 if (c->GetVerifyErrorClass() != NULL) {
128 // TODO: change the verifier to store an _instance_, with a useful detail message?
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800129 ClassHelper ve_ch(c->GetVerifyErrorClass());
130 std::string error_descriptor(ve_ch.GetDescriptor());
131 Thread::Current()->ThrowNewException(error_descriptor.c_str(), PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700132 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800133 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700134 }
135}
136
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700137static void WrapExceptionInInitializer()
Ian Rogersb726dcb2012-09-05 08:57:23 -0700138 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700139 Thread* self = Thread::Current();
140 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700141
142 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
143 CHECK(cause.get() != NULL);
144
145 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700146 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
147 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700148
Elliott Hughesa4f94742012-05-29 16:28:38 -0700149 // We only wrap non-Error exceptions; an Error can just be used as-is.
150 if (!is_error) {
151 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", NULL);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700152 }
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700153}
154
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800155static size_t Hash(const char* s) {
156 // This is the java.lang.String hashcode for convenience, not interoperability.
157 size_t hash = 0;
158 for (; *s != '\0'; ++s) {
159 hash = hash * 31 + *s;
160 }
161 return hash;
162}
163
Elliott Hughes418d20f2011-09-22 14:00:39 -0700164const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700165 "Ljava/lang/Class;",
166 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700167 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700168 "[Ljava/lang/Object;",
Ian Rogers23435d02012-09-24 11:23:12 -0700169 "[[Ljava/lang/Object;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700170 "Ljava/lang/String;",
Mathieu Chartier66f19252012-09-18 08:57:04 -0700171 "Ljava/lang/DexCache;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700172 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700173 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700174 "Ljava/lang/reflect/Field;",
Mathieu Chartier66f19252012-09-18 08:57:04 -0700175 "Ljava/lang/reflect/AbstractMethod;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700176 "Ljava/lang/reflect/Method;",
Ian Rogers466bb252011-10-14 03:29:56 -0700177 "Ljava/lang/reflect/Proxy;",
Mathieu Chartier66f19252012-09-18 08:57:04 -0700178 "[Ljava/lang/String;",
179 "[Ljava/lang/reflect/Field;",
180 "[Ljava/lang/reflect/AbstractMethod;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700181 "Ljava/lang/ClassLoader;",
Ian Rogers5167c972012-02-03 10:41:20 -0800182 "Ljava/lang/Throwable;",
jeffhao8cd6dda2012-02-22 10:15:34 -0800183 "Ljava/lang/ClassNotFoundException;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700184 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700185 "Z",
186 "B",
187 "C",
188 "D",
189 "F",
190 "I",
191 "J",
192 "S",
193 "V",
194 "[Z",
195 "[B",
196 "[C",
197 "[D",
198 "[F",
199 "[I",
200 "[J",
201 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700202 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700203};
204
Brian Carlstroma004aa92012-02-08 18:05:09 -0800205ClassLinker* ClassLinker::CreateFromCompiler(const std::vector<const DexFile*>& boot_class_path,
206 InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700207 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800208 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800209 class_linker->InitFromCompiler(boot_class_path);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700210 return class_linker.release();
211}
212
Brian Carlstroma004aa92012-02-08 18:05:09 -0800213ClassLinker* ClassLinker::CreateFromImage(InternTable* intern_table) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800214 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700215 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700216 return class_linker.release();
217}
218
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800219ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700220 // dex_lock_ is recursive as it may be used in stack dumping.
221 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel, true),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700222 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700223 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700224 init_done_(false),
225 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700226 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700227}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700228
Brian Carlstroma004aa92012-02-08 18:05:09 -0800229void ClassLinker::InitFromCompiler(const std::vector<const DexFile*>& boot_class_path) {
230 VLOG(startup) << "ClassLinker::Init";
231 CHECK(Runtime::Current()->IsCompiler());
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700232
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700233 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700234
Elliott Hughes30646832011-10-13 16:59:46 -0700235 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700236 Thread* self = Thread::Current();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800237 Heap* heap = Runtime::Current()->GetHeap();
Ian Rogers50b35e22012-10-04 10:09:15 -0700238 SirtRef<Class>
239 java_lang_Class(self, down_cast<Class*>(heap->AllocObject(self, NULL, sizeof(ClassClass))));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700240 CHECK(java_lang_Class.get() != NULL);
241 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700242 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700243 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700244
Elliott Hughes418d20f2011-09-22 14:00:39 -0700245 // Class[] is used for reflection support.
Ian Rogers50b35e22012-10-04 10:09:15 -0700246 SirtRef<Class> class_array_class(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700247 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700248
Ian Rogers23435d02012-09-24 11:23:12 -0700249 // java_lang_Object comes next so that object_array_class can be created.
Ian Rogers50b35e22012-10-04 10:09:15 -0700250 SirtRef<Class> java_lang_Object(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700251 CHECK(java_lang_Object.get() != NULL);
Ian Rogers23435d02012-09-24 11:23:12 -0700252 // backfill Object as the super class of Class.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700253 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700254 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700255
Ian Rogers23435d02012-09-24 11:23:12 -0700256 // Object[] next to hold class roots.
Ian Rogers50b35e22012-10-04 10:09:15 -0700257 SirtRef<Class> object_array_class(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700258 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700259
Ian Rogers23435d02012-09-24 11:23:12 -0700260 // Object[][] needed for iftables.
Ian Rogers50b35e22012-10-04 10:09:15 -0700261 SirtRef<Class> object_array_array_class(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Ian Rogers23435d02012-09-24 11:23:12 -0700262 object_array_array_class->SetComponentType(object_array_class.get());
263
264 // Setup the char class to be used for char[].
Ian Rogers50b35e22012-10-04 10:09:15 -0700265 SirtRef<Class> char_class(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700266
Ian Rogers23435d02012-09-24 11:23:12 -0700267 // Setup the char[] class to be used for String.
Ian Rogers50b35e22012-10-04 10:09:15 -0700268 SirtRef<Class> char_array_class(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700269 char_array_class->SetComponentType(char_class.get());
270 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700271
Ian Rogers23435d02012-09-24 11:23:12 -0700272 // Setup String.
Ian Rogers50b35e22012-10-04 10:09:15 -0700273 SirtRef<Class> java_lang_String(self, AllocClass(self, java_lang_Class.get(), sizeof(StringClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700274 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700275 java_lang_String->SetObjectSize(sizeof(String));
276 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400277
Ian Rogers23435d02012-09-24 11:23:12 -0700278 // Create storage for root classes, save away our work so far (requires descriptors).
Ian Rogers50b35e22012-10-04 10:09:15 -0700279 class_roots_ = ObjectArray<Class>::Alloc(self, object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700280 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700281 SetClassRoot(kJavaLangClass, java_lang_Class.get());
282 SetClassRoot(kJavaLangObject, java_lang_Object.get());
283 SetClassRoot(kClassArrayClass, class_array_class.get());
284 SetClassRoot(kObjectArrayClass, object_array_class.get());
Ian Rogers23435d02012-09-24 11:23:12 -0700285 SetClassRoot(kObjectArrayArrayClass, object_array_array_class.get());
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700286 SetClassRoot(kCharArrayClass, char_array_class.get());
287 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700288
289 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700290 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
291 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
292 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
293 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
294 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
295 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
296 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
297 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700298
Ian Rogers23435d02012-09-24 11:23:12 -0700299 // Create array interface entries to populate once we can load system classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700300 array_iftable_ = AllocIfTable(self, 2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700301
Ian Rogers23435d02012-09-24 11:23:12 -0700302 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Ian Rogers50b35e22012-10-04 10:09:15 -0700303 SirtRef<Class> int_array_class(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700304 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700305 IntArray::SetArrayClass(int_array_class.get());
306 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700307
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700308 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700309
Mathieu Chartier66f19252012-09-18 08:57:04 -0700310 // Setup DexCache. This can not be done later since AppendToBootClassPath calls AllocDexCache.
Ian Rogers50b35e22012-10-04 10:09:15 -0700311 SirtRef<Class>
312 java_lang_DexCache(self, AllocClass(self, java_lang_Class.get(), sizeof(DexCacheClass)));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700313 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.get());
314 java_lang_DexCache->SetObjectSize(sizeof(DexCacheClass));
315 java_lang_DexCache->SetStatus(Class::kStatusResolved);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700316
Mathieu Chartier66f19252012-09-18 08:57:04 -0700317 // Constructor, Field, Method, and AbstractMethod are necessary so that FindClass can link members.
Ian Rogers50b35e22012-10-04 10:09:15 -0700318 SirtRef<Class> java_lang_reflect_Constructor(self, AllocClass(self, java_lang_Class.get(),
319 sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700320 CHECK(java_lang_reflect_Constructor.get() != NULL);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700321 java_lang_reflect_Constructor->SetObjectSize(sizeof(Constructor));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700322 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700323 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
324
Ian Rogers50b35e22012-10-04 10:09:15 -0700325 SirtRef<Class> java_lang_reflect_Field(self, AllocClass(self, java_lang_Class.get(),
326 sizeof(FieldClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700327 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700328 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700329 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700330 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700331 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700332
Ian Rogers50b35e22012-10-04 10:09:15 -0700333 SirtRef<Class> java_lang_reflect_Method(self, AllocClass(self, java_lang_Class.get(),
334 sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700335 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700336 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700337 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700338 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700339
Ian Rogers50b35e22012-10-04 10:09:15 -0700340 SirtRef<Class> java_lang_reflect_AbstractMethod(self, AllocClass(self, java_lang_Class.get(),
341 sizeof(MethodClass)));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700342 CHECK(java_lang_reflect_AbstractMethod.get() != NULL);
343 java_lang_reflect_AbstractMethod->SetObjectSize(sizeof(AbstractMethod));
344 SetClassRoot(kJavaLangReflectAbstractMethod, java_lang_reflect_AbstractMethod.get());
345 java_lang_reflect_AbstractMethod->SetStatus(Class::kStatusResolved);
346 AbstractMethod::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
347
348 // Set up array classes for string, field, method
Ian Rogers50b35e22012-10-04 10:09:15 -0700349 SirtRef<Class> object_array_string(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700350 object_array_string->SetComponentType(java_lang_String.get());
351 SetClassRoot(kJavaLangStringArrayClass, object_array_string.get());
352
Ian Rogers50b35e22012-10-04 10:09:15 -0700353 SirtRef<Class> object_array_field(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700354 object_array_field->SetComponentType(java_lang_reflect_Field.get());
355 SetClassRoot(kJavaLangReflectFieldArrayClass, object_array_field.get());
356
Ian Rogers50b35e22012-10-04 10:09:15 -0700357 SirtRef<Class> object_array_abstract_method(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700358 object_array_abstract_method->SetComponentType(java_lang_reflect_AbstractMethod.get());
359 SetClassRoot(kJavaLangReflectAbstractMethodArrayClass, object_array_abstract_method.get());
360
Ian Rogers23435d02012-09-24 11:23:12 -0700361 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
362 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
363 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700364 CHECK_NE(0U, boot_class_path.size());
365 for (size_t i = 0; i != boot_class_path.size(); ++i) {
366 const DexFile* dex_file = boot_class_path[i];
367 CHECK(dex_file != NULL);
368 AppendToBootClassPath(*dex_file);
369 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700370
371 // now we can use FindSystemClass
372
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700373 // run char class through InitializePrimitiveClass to finish init
Ian Rogersc8982582012-09-07 16:53:25 -0700374 InitializePrimitiveClass(char_class.get(), Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700375 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700376
Mathieu Chartier66f19252012-09-18 08:57:04 -0700377 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700378 java_lang_Object->SetStatus(Class::kStatusNotReady);
379 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700380 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700381 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
382 java_lang_String->SetStatus(Class::kStatusNotReady);
383 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700384 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700385 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700386 java_lang_DexCache->SetStatus(Class::kStatusNotReady);
387 Class* DexCache_class = FindSystemClass("Ljava/lang/DexCache;");
388 CHECK_EQ(java_lang_String.get(), String_class);
389 CHECK_EQ(java_lang_DexCache.get(), DexCache_class);
390 CHECK_EQ(java_lang_DexCache->GetObjectSize(), sizeof(DexCache));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700391
Ian Rogers23435d02012-09-24 11:23:12 -0700392 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700393 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
394 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
395
396 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
397 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
398
399 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700400 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700401
402 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
403 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
404
405 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700406 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700407
408 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
409 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
410
411 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
412 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
413
414 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
415 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
416
Elliott Hughes418d20f2011-09-22 14:00:39 -0700417 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700418 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700419
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700420 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700421 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700422
Ian Rogers23435d02012-09-24 11:23:12 -0700423 Class* found_object_array_array_class = FindSystemClass("[[Ljava/lang/Object;");
424 CHECK_EQ(object_array_array_class.get(), found_object_array_array_class);
425
426 // Setup the single, global copy of "iftable".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700427 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
428 CHECK(java_lang_Cloneable != NULL);
429 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
430 CHECK(java_io_Serializable != NULL);
Ian Rogers23435d02012-09-24 11:23:12 -0700431 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
432 // crawl up and explicitly list all of the supers as well.
Ian Rogers50b35e22012-10-04 10:09:15 -0700433 array_iftable_->Set(0, AllocInterfaceEntry(self, java_lang_Cloneable));
434 array_iftable_->Set(1, AllocInterfaceEntry(self, java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700435
Ian Rogers23435d02012-09-24 11:23:12 -0700436 // Sanity check Class[] and Object[]'s interfaces.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800437 ClassHelper kh(class_array_class.get(), this);
Ian Rogersd24e2642012-06-06 21:21:43 -0700438 CHECK_EQ(java_lang_Cloneable, kh.GetDirectInterface(0));
439 CHECK_EQ(java_io_Serializable, kh.GetDirectInterface(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800440 kh.ChangeClass(object_array_class.get());
Ian Rogersd24e2642012-06-06 21:21:43 -0700441 CHECK_EQ(java_lang_Cloneable, kh.GetDirectInterface(0));
442 CHECK_EQ(java_io_Serializable, kh.GetDirectInterface(1));
Ian Rogers23435d02012-09-24 11:23:12 -0700443 // Run Class, Constructor, Field, and Method through FindSystemClass. This initializes their
444 // dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700445 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700446 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700447
Mathieu Chartier66f19252012-09-18 08:57:04 -0700448 java_lang_reflect_AbstractMethod->SetStatus(Class::kStatusNotReady);
449 Class* Abstract_method_class = FindSystemClass("Ljava/lang/reflect/AbstractMethod;");
450 CHECK_EQ(java_lang_reflect_AbstractMethod.get(), Abstract_method_class);
451
452 // Method extends AbstractMethod so must reset after.
453 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
454 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
455 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
456
457 // Constructor extends AbstractMethod so must reset after.
Elliott Hughes80609252011-09-23 17:24:51 -0700458 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
459 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700460 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700461
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700462 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700463 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700464 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700465
Mathieu Chartier66f19252012-09-18 08:57:04 -0700466 Class* String_array_class = FindSystemClass(class_roots_descriptors_[kJavaLangStringArrayClass]);
467 CHECK_EQ(object_array_string.get(), String_array_class);
468
469 Class* Field_array_class = FindSystemClass(class_roots_descriptors_[kJavaLangReflectFieldArrayClass]);
470 CHECK_EQ(object_array_field.get(), Field_array_class);
471
472 Class* Abstract_method_array_class =
473 FindSystemClass(class_roots_descriptors_[kJavaLangReflectAbstractMethodArrayClass]);
474 CHECK_EQ(object_array_abstract_method.get(), Abstract_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700475
Ian Rogers23435d02012-09-24 11:23:12 -0700476 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700477
Ian Rogers23435d02012-09-24 11:23:12 -0700478 // Create java.lang.reflect.Proxy root.
Ian Rogers466bb252011-10-14 03:29:56 -0700479 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
480 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
481
Brian Carlstrom1f870082011-08-23 16:02:11 -0700482 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700483 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
484 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700485 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700486 java_lang_ref_FinalizerReference->SetAccessFlags(
487 java_lang_ref_FinalizerReference->GetAccessFlags() |
488 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700489 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700490 java_lang_ref_PhantomReference->SetAccessFlags(
491 java_lang_ref_PhantomReference->GetAccessFlags() |
492 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700493 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700494 java_lang_ref_SoftReference->SetAccessFlags(
495 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700496 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700497 java_lang_ref_WeakReference->SetAccessFlags(
498 java_lang_ref_WeakReference->GetAccessFlags() |
499 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700500
Ian Rogers23435d02012-09-24 11:23:12 -0700501 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700502 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700503 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700504 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
505
jeffhao8cd6dda2012-02-22 10:15:34 -0800506 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700507 // java.lang.StackTraceElement as a convenience.
Ian Rogers5167c972012-02-03 10:41:20 -0800508 SetClassRoot(kJavaLangThrowable, FindSystemClass("Ljava/lang/Throwable;"));
509 Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
jeffhao8cd6dda2012-02-22 10:15:34 -0800510 SetClassRoot(kJavaLangClassNotFoundException, FindSystemClass("Ljava/lang/ClassNotFoundException;"));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700511 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
512 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700513 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700514
Brian Carlstroma663ea52011-08-19 23:33:41 -0700515 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700516
Brian Carlstroma004aa92012-02-08 18:05:09 -0800517 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700518}
519
520void ClassLinker::FinishInit() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800521 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700522
523 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700524 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700525 // as the types of the field can't be resolved prior to the runtime being
526 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700527 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700528 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700529 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
530
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800531 const DexFile& java_lang_dex = FindDexFile(java_lang_ref_Reference->GetDexCache());
532
Brian Carlstrom16192862011-09-12 17:50:06 -0700533 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800534 FieldHelper fh(pendingNext, this);
535 CHECK_STREQ(fh.GetName(), "pendingNext");
536 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
537 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700538
539 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800540 fh.ChangeField(queue);
541 CHECK_STREQ(fh.GetName(), "queue");
542 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
543 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700544
545 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800546 fh.ChangeField(queueNext);
547 CHECK_STREQ(fh.GetName(), "queueNext");
548 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
549 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700550
551 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800552 fh.ChangeField(referent);
553 CHECK_STREQ(fh.GetName(), "referent");
554 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
555 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700556
557 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800558 fh.ChangeField(zombie);
559 CHECK_STREQ(fh.GetName(), "zombie");
560 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
561 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700562
Elliott Hughesa4f94742012-05-29 16:28:38 -0700563 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800564 heap->SetReferenceOffsets(referent->GetOffset(),
Brian Carlstrom16192862011-09-12 17:50:06 -0700565 queue->GetOffset(),
566 queueNext->GetOffset(),
567 pendingNext->GetOffset(),
568 zombie->GetOffset());
569
Brian Carlstroma663ea52011-08-19 23:33:41 -0700570 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700571 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700572 ClassRoot class_root = static_cast<ClassRoot>(i);
573 Class* klass = GetClassRoot(class_root);
574 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700575 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700576 // note SetClassRoot does additional validation.
577 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700578 }
579
Elliott Hughes92f14b22011-10-06 12:29:54 -0700580 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700581
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700582 // disable the slow paths in FindClass and CreatePrimitiveClass now
583 // that Object, Class, and Object[] are setup
584 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700585
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800586 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700587}
588
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700589void ClassLinker::RunRootClinits() {
590 Thread* self = Thread::Current();
591 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
592 Class* c = GetClassRoot(ClassRoot(i));
593 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Ian Rogers0045a292012-03-31 21:08:41 -0700594 EnsureInitialized(GetClassRoot(ClassRoot(i)), true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700595 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700596 }
597 }
598}
599
Brian Carlstromd601af82012-01-06 10:15:19 -0800600bool ClassLinker::GenerateOatFile(const std::string& dex_filename,
601 int oat_fd,
602 const std::string& oat_cache_filename) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800603 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -0700604 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800605 const char* dex2oat = dex2oat_string.c_str();
606
Brian Carlstroma004aa92012-02-08 18:05:09 -0800607 const char* class_path = Runtime::Current()->GetClassPathString().c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800608
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800609 Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800610 std::string boot_image_option_string("--boot-image=");
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700611 boot_image_option_string += heap->GetImageSpace()->GetImageFilename();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800612 const char* boot_image_option = boot_image_option_string.c_str();
613
614 std::string dex_file_option_string("--dex-file=");
Brian Carlstromd601af82012-01-06 10:15:19 -0800615 dex_file_option_string += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800616 const char* dex_file_option = dex_file_option_string.c_str();
617
Brian Carlstromd601af82012-01-06 10:15:19 -0800618 std::string oat_fd_option_string("--oat-fd=");
Brian Carlstrom866c8622012-01-06 16:35:13 -0800619 StringAppendF(&oat_fd_option_string, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800620 const char* oat_fd_option = oat_fd_option_string.c_str();
621
Brian Carlstroma004aa92012-02-08 18:05:09 -0800622 std::string oat_location_option_string("--oat-location=");
623 oat_location_option_string += oat_cache_filename;
624 const char* oat_location_option = oat_location_option_string.c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800625
jeffhao262bf462011-10-20 18:36:32 -0700626 // fork and exec dex2oat
627 pid_t pid = fork();
628 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800629 // no allocation allowed between fork and exec
Ian Rogers725aee52012-01-11 11:56:56 -0800630
631 // change process groups, so we don't get reaped by ProcessManager
632 setpgid(0, 0);
633
jeffhao10037c82012-01-23 15:06:23 -0800634 VLOG(class_linker) << dex2oat
635 << " --runtime-arg -Xms64m"
636 << " --runtime-arg -Xmx64m"
637 << " --runtime-arg -classpath"
638 << " --runtime-arg " << class_path
639 << " " << boot_image_option
640 << " " << dex_file_option
641 << " " << oat_fd_option
Brian Carlstroma004aa92012-02-08 18:05:09 -0800642 << " " << oat_location_option;
jeffhao10037c82012-01-23 15:06:23 -0800643
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800644 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700645 "--runtime-arg", "-Xms64m",
646 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500647 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800648 "--runtime-arg", class_path,
649 boot_image_option,
650 dex_file_option,
Brian Carlstromd601af82012-01-06 10:15:19 -0800651 oat_fd_option,
Brian Carlstroma004aa92012-02-08 18:05:09 -0800652 oat_location_option,
jeffhao262bf462011-10-20 18:36:32 -0700653 NULL);
654
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800655 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
Brian Carlstromd601af82012-01-06 10:15:19 -0800656 return false;
jeffhao262bf462011-10-20 18:36:32 -0700657 } else {
658 // wait for dex2oat to finish
659 int status;
660 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
661 if (got_pid != pid) {
662 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
Brian Carlstromd601af82012-01-06 10:15:19 -0800663 return false;
jeffhao262bf462011-10-20 18:36:32 -0700664 }
665 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800666 LOG(ERROR) << dex2oat << " failed with dex-file=" << dex_filename;
667 return false;
jeffhao262bf462011-10-20 18:36:32 -0700668 }
669 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800670 return true;
jeffhao262bf462011-10-20 18:36:32 -0700671}
672
Brian Carlstrom866c8622012-01-06 16:35:13 -0800673void ClassLinker::RegisterOatFile(const OatFile& oat_file) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700674 MutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800675 RegisterOatFileLocked(oat_file);
676}
677
678void ClassLinker::RegisterOatFileLocked(const OatFile& oat_file) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700679 dex_lock_.AssertHeld(Thread::Current());
Brian Carlstrom866c8622012-01-06 16:35:13 -0800680 oat_files_.push_back(&oat_file);
681}
682
Ian Rogers30fab402012-01-23 15:43:46 -0800683OatFile* ClassLinker::OpenOat(const ImageSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700684 MutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700685 const Runtime* runtime = Runtime::Current();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700686 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800687 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
688 // check the down cast
689 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700690 std::string oat_filename;
691 oat_filename += runtime->GetHostPrefix();
692 oat_filename += oat_location->ToModifiedUtf8();
Logan Chien0c717dd2012-03-28 18:31:07 +0800693 OatFile* oat_file = OatFile::Open(oat_filename, oat_filename,
694 image_header.GetOatBegin(),
695 OatFile::kRelocNone);
Ian Rogers30fab402012-01-23 15:43:46 -0800696 VLOG(startup) << "ClassLinker::OpenOat entering oat_filename=" << oat_filename;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700697 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700698 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700699 return NULL;
700 }
701 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
702 uint32_t image_oat_checksum = image_header.GetOatChecksum();
703 if (oat_checksum != image_oat_checksum) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800704 LOG(ERROR) << "Failed to match oat file checksum " << std::hex << oat_checksum
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700705 << " to expected oat checksum " << std::hex << oat_checksum
706 << " in image";
707 return NULL;
708 }
Brian Carlstrom866c8622012-01-06 16:35:13 -0800709 RegisterOatFileLocked(*oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800710 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700711 return oat_file;
712}
713
Brian Carlstromae826982011-11-09 01:33:42 -0800714const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700715 MutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstroma004aa92012-02-08 18:05:09 -0800716 return FindOpenedOatFileFromDexLocation(dex_file.GetLocation());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800717}
718
Brian Carlstroma004aa92012-02-08 18:05:09 -0800719const OatFile* ClassLinker::FindOpenedOatFileFromDexLocation(const std::string& dex_location) {
Brian Carlstromae826982011-11-09 01:33:42 -0800720 for (size_t i = 0; i < oat_files_.size(); i++) {
721 const OatFile* oat_file = oat_files_[i];
722 DCHECK(oat_file != NULL);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800723 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, false);
Brian Carlstroma004aa92012-02-08 18:05:09 -0800724 if (oat_dex_file != NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800725 return oat_file;
726 }
727 }
728 return NULL;
729}
730
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800731static const DexFile* FindDexFileInOatLocation(const std::string& dex_location,
732 uint32_t dex_location_checksum,
733 const std::string& oat_location) {
Logan Chien0c717dd2012-03-28 18:31:07 +0800734 UniquePtr<OatFile> oat_file(
735 OatFile::Open(oat_location, oat_location, NULL, OatFile::kRelocAll));
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800736 if (oat_file.get() == NULL) {
737 return NULL;
738 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700739 Runtime* runtime = Runtime::Current();
740 const ImageHeader& image_header = runtime->GetHeap()->GetImageSpace()->GetImageHeader();
741 if (oat_file->GetOatHeader().GetImageFileLocationChecksum() != image_header.GetOatChecksum()) {
742 return NULL;
743 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800744 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
745 if (oat_dex_file == NULL) {
746 return NULL;
747 }
748 if (oat_dex_file->GetDexFileLocationChecksum() != dex_location_checksum) {
749 return NULL;
750 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700751 runtime->GetClassLinker()->RegisterOatFile(*oat_file.release());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800752 return oat_dex_file->OpenDexFile();
753}
754
755const DexFile* ClassLinker::FindOrCreateOatFileForDexLocation(const std::string& dex_location,
756 const std::string& oat_location) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700757 MutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700758 return FindOrCreateOatFileForDexLocationLocked(dex_location, oat_location);
759}
760
761const DexFile* ClassLinker::FindOrCreateOatFileForDexLocationLocked(const std::string& dex_location,
762 const std::string& oat_location) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800763 uint32_t dex_location_checksum;
764 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) {
765 LOG(ERROR) << "Failed to compute checksum '" << dex_location << "'";
766 return NULL;
767 }
768
769 // Check if we already have an up-to-date output file
770 const DexFile* dex_file = FindDexFileInOatLocation(dex_location,
771 dex_location_checksum,
772 oat_location);
773 if (dex_file != NULL) {
774 return dex_file;
775 }
776
777 // Generate the output oat file for the dex file
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800778 UniquePtr<File> file(OS::OpenFile(oat_location.c_str(), true));
779 if (file.get() == NULL) {
780 LOG(ERROR) << "Failed to create oat file: " << oat_location;
781 return NULL;
782 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700783 if (!GenerateOatFile(dex_location, file->Fd(), oat_location)) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800784 LOG(ERROR) << "Failed to generate oat file: " << oat_location;
785 return NULL;
786 }
787 // Open the oat from file descriptor we passed to GenerateOatFile
788 if (lseek(file->Fd(), 0, SEEK_SET) != 0) {
789 LOG(ERROR) << "Failed to seek to start of generated oat file: " << oat_location;
790 return NULL;
791 }
Logan Chien0c717dd2012-03-28 18:31:07 +0800792 const OatFile* oat_file =
793 OatFile::Open(*file.get(), oat_location, NULL, OatFile::kRelocAll);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800794 if (oat_file == NULL) {
795 LOG(ERROR) << "Failed to open generated oat file: " << oat_location;
796 return NULL;
797 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700798 RegisterOatFileLocked(*oat_file);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800799 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
800 if (oat_dex_file == NULL) {
801 LOG(ERROR) << "Failed to find dex file in generated oat file: " << oat_location;
802 return NULL;
803 }
804 return oat_dex_file->OpenDexFile();
805}
806
Brian Carlstromafe25512012-06-27 17:02:58 -0700807bool ClassLinker::VerifyOatFileChecksums(const OatFile* oat_file,
808 const std::string& dex_location,
809 uint32_t dex_location_checksum) {
810 Runtime* runtime = Runtime::Current();
811 const ImageHeader& image_header = runtime->GetHeap()->GetImageSpace()->GetImageHeader();
812 uint32_t image_checksum = image_header.GetOatChecksum();
813 bool image_check = (oat_file->GetOatHeader().GetImageFileLocationChecksum() == image_checksum);
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700814
Brian Carlstromafe25512012-06-27 17:02:58 -0700815 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
816 if (oat_dex_file == NULL) {
817 LOG(ERROR) << ".oat file " << oat_file->GetLocation()
818 << " does not contain contents for " << dex_location;
819 std::vector<const OatFile::OatDexFile*> oat_dex_files = oat_file->GetOatDexFiles();
820 for (size_t i = 0; i < oat_dex_files.size(); i++) {
821 const OatFile::OatDexFile* oat_dex_file = oat_dex_files[i];
822 LOG(ERROR) << ".oat file " << oat_file->GetLocation()
823 << " contains contents for " << oat_dex_file->GetDexFileLocation();
824 }
825 return false;
826 }
827 bool dex_check = (dex_location_checksum == oat_dex_file->GetDexFileLocationChecksum());
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700828
Brian Carlstromafe25512012-06-27 17:02:58 -0700829 if (image_check && dex_check) {
830 return true;
831 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700832
Brian Carlstromafe25512012-06-27 17:02:58 -0700833 if (!image_check) {
834 std::string image_file(image_header.GetImageRoot(
835 ImageHeader::kOatLocation)->AsString()->ToModifiedUtf8());
836 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
837 << " checksum ( " << std::hex << oat_dex_file->GetDexFileLocationChecksum()
838 << ") mismatch with " << image_file
839 << " (" << std::hex << image_checksum << ")";
840 }
841 if (!dex_check) {
842 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
843 << " checksum ( " << std::hex << oat_dex_file->GetDexFileLocationChecksum()
844 << ") mismatch with " << dex_location
845 << " (" << std::hex << dex_location_checksum << ")";
846 }
847 return false;
848}
849
850const DexFile* ClassLinker::VerifyAndOpenDexFileFromOatFile(const OatFile* oat_file,
851 const std::string& dex_location,
852 uint32_t dex_location_checksum) {
853 bool verified = VerifyOatFileChecksums(oat_file, dex_location, dex_location_checksum);
854 if (!verified) {
855 return NULL;
856 }
857 RegisterOatFileLocked(*oat_file);
858 return oat_file->GetOatDexFile(dex_location)->OpenDexFile();
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700859}
860
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800861const DexFile* ClassLinker::FindDexFileInOatFileFromDexLocation(const std::string& dex_location) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700862 MutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800863
Brian Carlstroma004aa92012-02-08 18:05:09 -0800864 const OatFile* open_oat_file = FindOpenedOatFileFromDexLocation(dex_location);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800865 if (open_oat_file != NULL) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800866 return open_oat_file->GetOatDexFile(dex_location)->OpenDexFile();
Brian Carlstromae826982011-11-09 01:33:42 -0800867 }
868
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700869 // Look for an existing file next to dex. for example, for
870 // /foo/bar/baz.jar, look for /foo/bar/baz.jar.oat.
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800871 std::string oat_filename(OatFile::DexFilenameToOatFilename(dex_location));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700872 const OatFile* oat_file = FindOatFileFromOatLocationLocked(oat_filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800873 if (oat_file != NULL) {
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700874 uint32_t dex_location_checksum;
875 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) {
876 // If no classes.dex found in dex_location, it has been stripped, assume oat is up-to-date.
877 // This is the common case in user builds for jar's and apk's in the /system directory.
878 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
879 CHECK(oat_dex_file != NULL) << oat_filename << " " << dex_location;
880 RegisterOatFileLocked(*oat_file);
881 return oat_dex_file->OpenDexFile();
882 }
Brian Carlstromafe25512012-06-27 17:02:58 -0700883 const DexFile* dex_file = VerifyAndOpenDexFileFromOatFile(oat_file,
884 dex_location,
885 dex_location_checksum);
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700886 if (dex_file != NULL) {
887 return dex_file;
888 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800889 }
890 // Look for an existing file in the art-cache, validating the result if found
891 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
892 std::string cache_location(GetArtCacheFilenameOrDie(oat_filename));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700893 oat_file = FindOatFileFromOatLocationLocked(cache_location);
Brian Carlstroma004aa92012-02-08 18:05:09 -0800894 if (oat_file != NULL) {
895 uint32_t dex_location_checksum;
896 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) {
897 LOG(WARNING) << "Failed to compute checksum: " << dex_location;
898 return NULL;
899 }
Brian Carlstromafe25512012-06-27 17:02:58 -0700900 const DexFile* dex_file = VerifyAndOpenDexFileFromOatFile(oat_file,
901 dex_location,
902 dex_location_checksum);
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700903 if (dex_file != NULL) {
904 return dex_file;
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700905 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800906 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
Brian Carlstrom5ef74932012-03-23 17:56:02 -0700907 PLOG(FATAL) << "Failed to remove obsolete .oat file " << oat_file->GetLocation();
Brian Carlstromd601af82012-01-06 10:15:19 -0800908 }
jeffhao262bf462011-10-20 18:36:32 -0700909 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800910 LOG(INFO) << "Failed to open oat file from " << oat_filename << " or " << cache_location << ".";
911
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800912 // Try to generate oat file if it wasn't found or was obsolete.
913 std::string oat_cache_filename(GetArtCacheFilenameOrDie(oat_filename));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700914 return FindOrCreateOatFileForDexLocationLocked(dex_location, oat_cache_filename);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700915}
916
Brian Carlstromae826982011-11-09 01:33:42 -0800917const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700918 for (size_t i = 0; i < oat_files_.size(); i++) {
919 const OatFile* oat_file = oat_files_[i];
920 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800921 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700922 return oat_file;
923 }
924 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700925 return NULL;
926}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700927
Brian Carlstromae826982011-11-09 01:33:42 -0800928const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700929 MutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700930 return FindOatFileFromOatLocationLocked(oat_location);
931}
932
933const OatFile* ClassLinker::FindOatFileFromOatLocationLocked(const std::string& oat_location) {
jeffhaof6174e82012-01-31 16:14:17 -0800934 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
935 if (oat_file != NULL) {
936 return oat_file;
937 }
938
Logan Chien0c717dd2012-03-28 18:31:07 +0800939 oat_file = OatFile::Open(oat_location, oat_location, NULL,
940 OatFile::kRelocAll);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700941 if (oat_file == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800942 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700943 }
Brian Carlstromae826982011-11-09 01:33:42 -0800944 CHECK(oat_file != NULL) << oat_location;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700945 return oat_file;
946}
947
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700948void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800949 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700950 CHECK(!init_done_);
951
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800952 Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700953 ImageSpace* space = heap->GetImageSpace();
954 OatFile* oat_file = OpenOat(space);
955 CHECK(oat_file != NULL) << "Failed to open oat file for image";
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700956 CHECK_EQ(oat_file->GetOatHeader().GetImageFileLocationChecksum(), 0U);
Elliott Hughes74847412012-06-20 18:10:21 -0700957 CHECK(oat_file->GetOatHeader().GetImageFileLocation().empty());
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700958 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
959 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700960
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700961 // Special case of setting up the String class early so that we can test arbitrary objects
962 // as being Strings or not
963 Class* java_lang_String = space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
964 ->AsObjectArray<Class>()->Get(kJavaLangString);
965 String::SetClass(java_lang_String);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800966
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700967 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
968 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers1f539342012-10-03 21:09:42 -0700969 Thread* self = Thread::Current();
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700970 for (int i = 0; i < dex_caches->GetLength(); i++) {
Ian Rogers1f539342012-10-03 21:09:42 -0700971 SirtRef<DexCache> dex_cache(self, dex_caches->Get(i));
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700972 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
973 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
974 const DexFile* dex_file = oat_dex_file->OpenDexFile();
975 if (dex_file == NULL) {
976 LOG(FATAL) << "Failed to open dex file " << dex_file_location
977 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700978 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700979
980 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
981
982 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700983 }
984
Brian Carlstroma663ea52011-08-19 23:33:41 -0700985 // reinit clases_ table
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700986 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700987 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700988 heap->FlushAllocStack();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -0700989 heap->GetLiveBitmap()->Walk(InitFromImageCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700990 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700991
992 // reinit class_roots_
Ian Rogers30fab402012-01-23 15:43:46 -0800993 Object* class_roots_object =
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700994 heap->GetImageSpace()->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700995 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700996
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800997 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700998 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
999 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001000 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001001 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001002 AbstractMethod::SetClasses(GetClassRoot(kJavaLangReflectConstructor),
1003 GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001004 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1005 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1006 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1007 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1008 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1009 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1010 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1011 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers5167c972012-02-03 10:41:20 -08001012 Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001013 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001014
1015 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001016
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001017 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001018}
1019
Brian Carlstrom78128a62011-09-15 17:21:19 -07001020void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001021 DCHECK(obj != NULL);
1022 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -07001023 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001024
Elliott Hughesdbb40792011-11-18 17:05:22 -08001025 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -07001026 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -07001027 return;
1028 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001029 if (obj->IsClass()) {
1030 // restore class to ClassLinker::classes_ table
1031 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001032 ClassHelper kh(klass, class_linker);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001033 Class* existing = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
1034 DCHECK(existing == NULL) << kh.GetDescriptor();
Brian Carlstroma663ea52011-08-19 23:33:41 -07001035 return;
1036 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001037}
1038
1039// Keep in sync with InitCallback. Anything we visit, we need to
1040// reinit references to when reinitializing a ClassLinker from a
1041// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -07001042void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
1043 visitor(class_roots_, arg);
Ian Rogers50b35e22012-10-04 10:09:15 -07001044 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001045 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001046 MutexLock mu(self, dex_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001047 for (size_t i = 0; i < dex_caches_.size(); i++) {
1048 visitor(dex_caches_[i], arg);
1049 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001050 }
1051
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001052 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001053 MutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001054 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001055 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -07001056 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001057 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001058
1059 // We deliberately ignore the class roots in the image since we
1060 // handle image roots by using the MS/CMS rescanning of dirty cards.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001061 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001062
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001063 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001064}
1065
Elliott Hughesa2155262011-11-16 16:26:58 -08001066void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
Ian Rogers50b35e22012-10-04 10:09:15 -07001067 MutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Elliott Hughesa2155262011-11-16 16:26:58 -08001068 typedef Table::const_iterator It; // TODO: C++0x auto
1069 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
1070 if (!visitor(it->second, arg)) {
1071 return;
1072 }
1073 }
1074 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
1075 if (!visitor(it->second, arg)) {
1076 return;
1077 }
1078 }
1079}
1080
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001081static bool GetClassesVisitor(Class* c, void* arg) {
1082 std::set<Class*>* classes = reinterpret_cast<std::set<Class*>*>(arg);
1083 classes->insert(c);
1084 return true;
1085}
1086
1087void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) const {
1088 std::set<Class*> classes;
1089 VisitClasses(GetClassesVisitor, &classes);
1090 typedef std::set<Class*>::const_iterator It; // TODO: C++0x auto
1091 for (It it = classes.begin(), end = classes.end(); it != end; ++it) {
1092 if (!visitor(*it, arg)) {
1093 return;
1094 }
1095 }
1096}
1097
1098
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001099ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001100 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001101 Field::ResetClass();
Mathieu Chartier66f19252012-09-18 08:57:04 -07001102 AbstractMethod::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001103 BooleanArray::ResetArrayClass();
1104 ByteArray::ResetArrayClass();
1105 CharArray::ResetArrayClass();
1106 DoubleArray::ResetArrayClass();
1107 FloatArray::ResetArrayClass();
1108 IntArray::ResetArrayClass();
1109 LongArray::ResetArrayClass();
1110 ShortArray::ResetArrayClass();
Ian Rogers5167c972012-02-03 10:41:20 -08001111 Throwable::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001112 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001113 STLDeleteElements(&boot_class_path_);
1114 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001115}
1116
Ian Rogers50b35e22012-10-04 10:09:15 -07001117DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001118 Heap* heap = Runtime::Current()->GetHeap();
1119 Class* dex_cache_class = GetClassRoot(kJavaLangDexCache);
Ian Rogers50b35e22012-10-04 10:09:15 -07001120 SirtRef<DexCache> dex_cache(self,
1121 down_cast<DexCache*>(heap->AllocObject(self, dex_cache_class,
1122 dex_cache_class->GetObjectSize())));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001123 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001124 return NULL;
1125 }
Ian Rogers1f539342012-10-03 21:09:42 -07001126 SirtRef<String> location(self, intern_table_->InternStrong(dex_file.GetLocation().c_str()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001127 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001128 return NULL;
1129 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001130 SirtRef<ObjectArray<String> > strings(self, AllocStringArray(self, dex_file.NumStringIds()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001131 if (strings.get() == NULL) {
1132 return NULL;
1133 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001134 SirtRef<ObjectArray<Class> > types(self, AllocClassArray(self, dex_file.NumTypeIds()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001135 if (types.get() == NULL) {
1136 return NULL;
1137 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001138 SirtRef<ObjectArray<AbstractMethod> >
1139 methods(self, AllocMethodArray(self, dex_file.NumMethodIds()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001140 if (methods.get() == NULL) {
1141 return NULL;
1142 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001143 SirtRef<ObjectArray<Field> > fields(self, AllocFieldArray(self, dex_file.NumFieldIds()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001144 if (fields.get() == NULL) {
1145 return NULL;
1146 }
Ian Rogers1f539342012-10-03 21:09:42 -07001147 SirtRef<ObjectArray<StaticStorageBase> >
Ian Rogers50b35e22012-10-04 10:09:15 -07001148 initialized_static_storage(self,
1149 AllocObjectArray<StaticStorageBase>(self, dex_file.NumTypeIds()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001150 if (initialized_static_storage.get() == NULL) {
1151 return NULL;
1152 }
1153
Mathieu Chartier66f19252012-09-18 08:57:04 -07001154 dex_cache->Init(&dex_file,
1155 location.get(),
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001156 strings.get(),
1157 types.get(),
1158 methods.get(),
1159 fields.get(),
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001160 initialized_static_storage.get());
1161 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001162}
1163
Ian Rogers50b35e22012-10-04 10:09:15 -07001164InterfaceEntry* ClassLinker::AllocInterfaceEntry(Thread* self, Class* interface) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001165 DCHECK(interface->IsInterface());
Ian Rogers50b35e22012-10-04 10:09:15 -07001166 SirtRef<ObjectArray<Object> > array(self, AllocObjectArray<Object>(self, InterfaceEntry::LengthAsArray()));
Ian Rogers1f539342012-10-03 21:09:42 -07001167 SirtRef<InterfaceEntry> interface_entry(self, down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001168 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001169 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001170}
1171
Ian Rogers50b35e22012-10-04 10:09:15 -07001172Class* ClassLinker::AllocClass(Thread* self, Class* java_lang_Class, size_t class_size) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001173 DCHECK_GE(class_size, sizeof(Class));
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001174 Heap* heap = Runtime::Current()->GetHeap();
Ian Rogers50b35e22012-10-04 10:09:15 -07001175 SirtRef<Class> klass(self,
1176 heap->AllocObject(self, java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001177 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001178 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001179 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001180}
1181
Ian Rogers50b35e22012-10-04 10:09:15 -07001182Class* ClassLinker::AllocClass(Thread* self, size_t class_size) {
1183 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001184}
1185
Ian Rogers50b35e22012-10-04 10:09:15 -07001186Field* ClassLinker::AllocField(Thread* self) {
1187 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001188}
1189
Ian Rogers50b35e22012-10-04 10:09:15 -07001190Method* ClassLinker::AllocMethod(Thread* self) {
1191 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject(self));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001192}
1193
Ian Rogers50b35e22012-10-04 10:09:15 -07001194Constructor* ClassLinker::AllocConstructor(Thread* self) {
1195 return down_cast<Constructor*>(GetClassRoot(kJavaLangReflectConstructor)->AllocObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001196}
1197
Ian Rogers50b35e22012-10-04 10:09:15 -07001198ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(Thread* self,
1199 size_t length) {
1200 return ObjectArray<StackTraceElement>::Alloc(self,
1201 GetClassRoot(kJavaLangStackTraceElementArrayClass),
1202 length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001203}
1204
Ian Rogers50b35e22012-10-04 10:09:15 -07001205static Class* EnsureResolved(Thread* self, Class* klass)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001206 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001207 DCHECK(klass != NULL);
1208 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001209 if (!klass->IsResolved() && !klass->IsErroneous()) {
Ian Rogers1f539342012-10-03 21:09:42 -07001210 ObjectLock lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001211 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001212 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001213 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001214 PrettyDescriptor(klass).c_str());
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001215 klass->SetStatus(Class::kStatusError);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001216 return NULL;
1217 }
1218 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001219 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001220 lock.Wait();
1221 }
1222 }
1223 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001224 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001225 return NULL;
1226 }
1227 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001228 CHECK(klass->IsResolved()) << PrettyClass(klass);
1229 CHECK(!self->IsExceptionPending())
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001230 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException()) << "\n"
1231 << self->GetException()->Dump();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001232 return klass;
1233}
1234
Elliott Hughesdb7d5e92011-12-16 18:47:37 -08001235Class* ClassLinker::FindSystemClass(const char* descriptor) {
1236 return FindClass(descriptor, NULL);
1237}
1238
Ian Rogers365c1022012-06-22 15:05:28 -07001239Class* ClassLinker::FindClass(const char* descriptor, ClassLoader* class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001240 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001241 Thread* self = Thread::Current();
1242 DCHECK(self != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001243 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001244 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001245 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1246 // for primitive classes that aren't backed by dex files.
1247 return FindPrimitiveClass(descriptor[0]);
1248 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001249 // Find the class in the loaded classes table.
1250 Class* klass = LookupClass(descriptor, class_loader);
1251 if (klass != NULL) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001252 return EnsureResolved(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001253 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001254 // Class is not yet loaded.
1255 if (descriptor[0] == '[') {
1256 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001257
Jesse Wilson47daf872011-11-23 11:42:45 -05001258 } else if (class_loader == NULL) {
1259 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1260 if (pair.second != NULL) {
1261 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1262 }
1263
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001264 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Jesse Wilson47daf872011-11-23 11:42:45 -05001265 // first try the boot class path
1266 Class* system_class = FindSystemClass(descriptor);
1267 if (system_class != NULL) {
1268 return system_class;
1269 }
1270 CHECK(self->IsExceptionPending());
1271 self->ClearException();
1272
1273 // next try the compile time class path
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001274 const std::vector<const DexFile*>* class_path;
1275 {
1276 ScopedObjectAccessUnchecked soa(Thread::Current());
1277 ScopedLocalRef<jobject> jclass_loader(soa.Env(), soa.AddLocalReference<jobject>(class_loader));
1278 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
1279 }
1280
1281 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, *class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001282 if (pair.second != NULL) {
1283 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001284 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001285
1286 } else {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001287 ScopedObjectAccessUnchecked soa(self->GetJniEnv());
1288 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
1289 soa.AddLocalReference<jobject>(class_loader));
Elliott Hughes95572412011-12-13 18:14:20 -08001290 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001291 ScopedLocalRef<jobject> result(soa.Env(), NULL);
Ian Rogers365c1022012-06-22 15:05:28 -07001292 {
1293 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001294 ScopedLocalRef<jobject> class_name_object(soa.Env(),
1295 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers365c1022012-06-22 15:05:28 -07001296 if (class_name_object.get() == NULL) {
1297 return NULL;
1298 }
1299 CHECK(class_loader_object.get() != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001300 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
1301 WellKnownClasses::java_lang_ClassLoader_loadClass,
1302 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05001303 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001304 if (soa.Env()->ExceptionCheck()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001305 // If the ClassLoader threw, pass that exception up.
1306 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001307 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001308 // broken loader - throw NPE to be compatible with Dalvik
1309 ThrowNullPointerException("ClassLoader.loadClass returned null for %s",
1310 class_name_string.c_str());
1311 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001312 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08001313 // success, return Class*
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001314 return soa.Decode<Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001315 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001316 }
1317
Elliott Hughes82914b62012-04-09 15:56:29 -07001318 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001319 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001320}
1321
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001322Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Ian Rogers365c1022012-06-22 15:05:28 -07001323 ClassLoader* class_loader,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001324 const DexFile& dex_file,
1325 const DexFile::ClassDef& dex_class_def) {
Ian Rogers1f539342012-10-03 21:09:42 -07001326 Thread* self = Thread::Current();
1327 SirtRef<Class> klass(self, NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001328 // Load the class from the dex file.
1329 if (!init_done_) {
1330 // finish up init of hand crafted class_roots_
1331 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001332 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001333 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001334 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001335 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001336 klass.reset(GetClassRoot(kJavaLangString));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001337 } else if (descriptor == "Ljava/lang/DexCache;") {
1338 klass.reset(GetClassRoot(kJavaLangDexCache));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001339 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001340 klass.reset(GetClassRoot(kJavaLangReflectField));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001341 } else if (descriptor == "Ljava/lang/reflect/AbstractMethod;") {
1342 klass.reset(GetClassRoot(kJavaLangReflectAbstractMethod));
1343 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
1344 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001345 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001346 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001347 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001348 klass.reset(AllocClass(self, SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001349 }
1350 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001351 klass.reset(AllocClass(self, SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001352 }
1353 klass->SetDexCache(FindDexCache(dex_file));
1354 LoadClass(dex_file, dex_class_def, klass, class_loader);
1355 // Check for a pending exception during load
Brian Carlstromaded5f72011-10-07 17:15:04 -07001356 if (self->IsExceptionPending()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001357 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001358 return NULL;
1359 }
Ian Rogers1f539342012-10-03 21:09:42 -07001360 ObjectLock lock(self, klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001361 klass->SetClinitThreadId(self->GetTid());
1362 // Add the newly loaded class to the loaded classes table.
Ian Rogers1f539342012-10-03 21:09:42 -07001363 SirtRef<Class> existing(self, InsertClass(descriptor, klass.get(), false));
Brian Carlstrom01e076e2012-03-30 11:54:16 -07001364 if (existing.get() != NULL) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001365 // We failed to insert because we raced with another thread.
Ian Rogers50b35e22012-10-04 10:09:15 -07001366 return EnsureResolved(self, existing.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001367 }
1368 // Finish loading (if necessary) by finding parents
1369 CHECK(!klass->IsLoaded());
1370 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1371 // Loading failed.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001372 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001373 lock.NotifyAll();
1374 return NULL;
1375 }
1376 CHECK(klass->IsLoaded());
1377 // Link the class (if necessary)
1378 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001379 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001380 // Linking failed.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001381 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001382 lock.NotifyAll();
1383 return NULL;
1384 }
1385 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001386
1387 /*
1388 * We send CLASS_PREPARE events to the debugger from here. The
1389 * definition of "preparation" is creating the static fields for a
1390 * class and initializing them to the standard default values, but not
1391 * executing any code (that comes later, during "initialization").
1392 *
1393 * We did the static preparation in LinkClass.
1394 *
1395 * The class has been prepared and resolved but possibly not yet verified
1396 * at this point.
1397 */
1398 Dbg::PostClassPrepare(klass.get());
1399
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001400 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001401}
1402
Brian Carlstrom4873d462011-08-21 15:23:39 -07001403// Precomputes size that will be needed for Class, matching LinkStaticFields
1404size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1405 const DexFile::ClassDef& dex_class_def) {
1406 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001407 size_t num_ref = 0;
1408 size_t num_32 = 0;
1409 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001410 if (class_data != NULL) {
1411 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1412 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001413 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001414 char c = descriptor[0];
1415 if (c == 'L' || c == '[') {
1416 num_ref++;
1417 } else if (c == 'J' || c == 'D') {
1418 num_64++;
1419 } else {
1420 num_32++;
1421 }
1422 }
1423 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001424 // start with generic class data
1425 size_t size = sizeof(Class);
1426 // follow with reference fields which must be contiguous at start
1427 size += (num_ref * sizeof(uint32_t));
1428 // if there are 64-bit fields to add, make sure they are aligned
1429 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1430 if (num_32 != 0) {
1431 // use an available 32-bit field for padding
1432 num_32--;
1433 }
1434 size += sizeof(uint32_t); // either way, we are adding a word
1435 DCHECK_EQ(size, RoundUp(size, 8));
1436 }
1437 // tack on any 64-bit fields now that alignment is assured
1438 size += (num_64 * sizeof(uint64_t));
1439 // tack on any remaining 32-bit fields
1440 size += (num_32 * sizeof(uint32_t));
1441 return size;
1442}
1443
Ian Rogers19846512012-02-24 11:42:47 -08001444const OatFile::OatClass* ClassLinker::GetOatClass(const DexFile& dex_file, const char* descriptor) {
1445 DCHECK(descriptor != NULL);
Ian Rogers19846512012-02-24 11:42:47 -08001446 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
1447 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << descriptor;
1448 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1449 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << descriptor;
1450 uint32_t class_def_index;
1451 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1452 CHECK(found) << dex_file.GetLocation() << " " << descriptor;
1453 const OatFile::OatClass* oat_class = oat_dex_file->GetOatClass(class_def_index);
1454 CHECK(oat_class != NULL) << dex_file.GetLocation() << " " << descriptor;
1455 return oat_class;
1456}
1457
Mathieu Chartier66f19252012-09-18 08:57:04 -07001458const OatFile::OatMethod ClassLinker::GetOatMethodFor(const AbstractMethod* method) {
Ian Rogers19846512012-02-24 11:42:47 -08001459 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08001460 // method for direct methods (or virtual methods made direct).
1461 Class* declaring_class = method->GetDeclaringClass();
1462 size_t oat_method_index;
1463 if (method->IsStatic() || method->IsDirect()) {
1464 // Simple case where the oat method index was stashed at load time.
1465 oat_method_index = method->GetMethodIndex();
1466 } else {
1467 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
1468 // by search for its position in the declared virtual methods.
1469 oat_method_index = declaring_class->NumDirectMethods();
1470 size_t end = declaring_class->NumVirtualMethods();
1471 bool found = false;
1472 for (size_t i = 0; i < end; i++) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08001473 if (declaring_class->GetVirtualMethod(i) == method) {
1474 found = true;
1475 break;
1476 }
Ian Rogersf320b632012-03-13 18:47:47 -07001477 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001478 }
1479 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method);
1480 }
1481 ClassHelper kh(declaring_class);
Ian Rogers19846512012-02-24 11:42:47 -08001482 UniquePtr<const OatFile::OatClass> oat_class(GetOatClass(kh.GetDexFile(), kh.GetDescriptor()));
Brian Carlstromf5822582012-03-19 22:34:31 -07001483 CHECK(oat_class.get() != NULL);
TDYa12785321912012-04-01 15:24:56 -07001484 return oat_class->GetOatMethod(oat_method_index);
1485}
1486
1487// Special case to get oat code without overwriting a trampoline.
Mathieu Chartier66f19252012-09-18 08:57:04 -07001488const void* ClassLinker::GetOatCodeFor(const AbstractMethod* method) {
TDYa127ccffd9e2012-04-08 14:37:03 -07001489 CHECK(Runtime::Current()->IsCompiler() || method->GetDeclaringClass()->IsInitializing());
TDYa12785321912012-04-01 15:24:56 -07001490 return GetOatMethodFor(method).GetCode();
1491}
1492
Ian Rogers19846512012-02-24 11:42:47 -08001493void ClassLinker::FixupStaticTrampolines(Class* klass) {
1494 ClassHelper kh(klass);
1495 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
1496 CHECK(dex_class_def != NULL);
1497 const DexFile& dex_file = kh.GetDexFile();
1498 const byte* class_data = dex_file.GetClassData(*dex_class_def);
1499 if (class_data == NULL) {
1500 return; // no fields or methods - for example a marker interface
1501 }
Brian Carlstromf5822582012-03-19 22:34:31 -07001502 if (!Runtime::Current()->IsStarted() || Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers19846512012-02-24 11:42:47 -08001503 // OAT file unavailable
1504 return;
1505 }
Brian Carlstromf5822582012-03-19 22:34:31 -07001506 UniquePtr<const OatFile::OatClass> oat_class(GetOatClass(dex_file, kh.GetDescriptor()));
1507 CHECK(oat_class.get() != NULL);
Ian Rogers19846512012-02-24 11:42:47 -08001508 ClassDataItemIterator it(dex_file, class_data);
1509 // Skip fields
1510 while (it.HasNextStaticField()) {
1511 it.Next();
1512 }
1513 while (it.HasNextInstanceField()) {
1514 it.Next();
1515 }
1516 size_t method_index = 0;
1517 // Link the code of methods skipped by LinkCode
1518 const void* trampoline = Runtime::Current()->GetResolutionStubArray(Runtime::kStaticMethod)->GetData();
1519 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001520 AbstractMethod* method = klass->GetDirectMethod(i);
jeffhaob5e81852012-03-12 11:15:45 -07001521 if (Runtime::Current()->IsMethodTracingActive()) {
1522 Trace* tracer = Runtime::Current()->GetTracer();
1523 if (tracer->GetSavedCodeFromMap(method) == trampoline) {
1524 const void* code = oat_class->GetOatMethod(method_index).GetCode();
1525 tracer->ResetSavedCode(method);
1526 method->SetCode(code);
1527 tracer->SaveAndUpdateCode(method);
1528 }
1529 } else if (method->GetCode() == trampoline) {
Ian Rogers19846512012-02-24 11:42:47 -08001530 const void* code = oat_class->GetOatMethod(method_index).GetCode();
Ian Rogers08f753d2012-08-24 14:35:25 -07001531 CHECK(code != NULL)
1532 << "Resolving a static trampoline but found no code for: " << PrettyMethod(method);
Ian Rogers19846512012-02-24 11:42:47 -08001533 method->SetCode(code);
1534 }
1535 method_index++;
1536 }
1537}
1538
Mathieu Chartier66f19252012-09-18 08:57:04 -07001539static void LinkCode(SirtRef<AbstractMethod>& method, const OatFile::OatClass* oat_class,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001540 uint32_t method_index)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001541 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001542 // Every kind of method should at least get an invoke stub from the oat_method.
1543 // non-abstract methods also get their code pointers.
1544 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001545 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001546
Ian Rogers19846512012-02-24 11:42:47 -08001547 Runtime* runtime = Runtime::Current();
Brian Carlstrom92827a52011-10-10 15:50:01 -07001548 if (method->IsAbstract()) {
Ian Rogers19846512012-02-24 11:42:47 -08001549 method->SetCode(runtime->GetAbstractMethodErrorStubArray()->GetData());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001550 return;
1551 }
Ian Rogers19846512012-02-24 11:42:47 -08001552
1553 if (method->IsStatic() && !method->IsConstructor()) {
1554 // For static methods excluding the class initializer, install the trampoline
1555 method->SetCode(runtime->GetResolutionStubArray(Runtime::kStaticMethod)->GetData());
Ian Rogers0d6de042012-02-29 08:50:26 -08001556 }
1557 if (method->IsNative()) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001558 // unregistering restores the dlsym lookup stub
Ian Rogers19846512012-02-24 11:42:47 -08001559 method->UnregisterNative(Thread::Current());
jeffhao26c0a1a2012-01-17 16:28:33 -08001560 }
1561
1562 if (Runtime::Current()->IsMethodTracingActive()) {
jeffhao26c0a1a2012-01-17 16:28:33 -08001563 Trace* tracer = Runtime::Current()->GetTracer();
jeffhaob5e81852012-03-12 11:15:45 -07001564 tracer->SaveAndUpdateCode(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001565 }
1566}
1567
Brian Carlstromf615a612011-07-23 12:50:34 -07001568void ClassLinker::LoadClass(const DexFile& dex_file,
1569 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001570 SirtRef<Class>& klass,
Ian Rogers365c1022012-06-22 15:05:28 -07001571 ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001572 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001573 CHECK(klass->GetDexCache() != NULL);
1574 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001575 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001576 CHECK(descriptor != NULL);
1577
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001578 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001579 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001580 // Make sure that none of our runtime-only flags are set.
1581 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001582 klass->SetAccessFlags(access_flags);
1583 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001584 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001585 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001586
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001587 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001588
Ian Rogers0571d352011-11-03 19:51:38 -07001589 // Load fields fields.
1590 const byte* class_data = dex_file.GetClassData(dex_class_def);
1591 if (class_data == NULL) {
1592 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001593 }
Ian Rogers0571d352011-11-03 19:51:38 -07001594 ClassDataItemIterator it(dex_file, class_data);
Ian Rogers50b35e22012-10-04 10:09:15 -07001595 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07001596 if (it.NumStaticFields() != 0) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001597 klass->SetSFields(AllocObjectArray<Field>(self, it.NumStaticFields()));
Ian Rogers0571d352011-11-03 19:51:38 -07001598 }
1599 if (it.NumInstanceFields() != 0) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001600 klass->SetIFields(AllocObjectArray<Field>(self, it.NumInstanceFields()));
Ian Rogers0571d352011-11-03 19:51:38 -07001601 }
1602 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001603 SirtRef<Field> sfield(self, AllocField(self));
Ian Rogers0571d352011-11-03 19:51:38 -07001604 klass->SetStaticField(i, sfield.get());
1605 LoadField(dex_file, it, klass, sfield);
1606 }
1607 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001608 SirtRef<Field> ifield(self, AllocField(self));
Ian Rogers0571d352011-11-03 19:51:38 -07001609 klass->SetInstanceField(i, ifield.get());
1610 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001611 }
1612
Brian Carlstromf5822582012-03-19 22:34:31 -07001613 UniquePtr<const OatFile::OatClass> oat_class;
1614 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
1615 oat_class.reset(GetOatClass(dex_file, descriptor));
1616 }
Ian Rogers19846512012-02-24 11:42:47 -08001617
Ian Rogers0571d352011-11-03 19:51:38 -07001618 // Load methods.
1619 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001620 // TODO: append direct methods to class object
Ian Rogers50b35e22012-10-04 10:09:15 -07001621 klass->SetDirectMethods(AllocObjectArray<AbstractMethod>(self, it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001622 }
Ian Rogers0571d352011-11-03 19:51:38 -07001623 if (it.NumVirtualMethods() != 0) {
1624 // TODO: append direct methods to class object
Ian Rogers50b35e22012-10-04 10:09:15 -07001625 klass->SetVirtualMethods(AllocObjectArray<AbstractMethod>(self, it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001626 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08001627 size_t class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001628 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001629 SirtRef<AbstractMethod> method(self, LoadMethod(self, dex_file, it, klass));
Ian Rogers0571d352011-11-03 19:51:38 -07001630 klass->SetDirectMethod(i, method.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001631 if (oat_class.get() != NULL) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08001632 LinkCode(method, oat_class.get(), class_def_method_index);
Ian Rogers0571d352011-11-03 19:51:38 -07001633 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08001634 method->SetMethodIndex(class_def_method_index);
1635 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001636 }
1637 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001638 SirtRef<AbstractMethod> method(self, LoadMethod(self, dex_file, it, klass));
Ian Rogers0571d352011-11-03 19:51:38 -07001639 klass->SetVirtualMethod(i, method.get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08001640 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers0571d352011-11-03 19:51:38 -07001641 if (oat_class.get() != NULL) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08001642 LinkCode(method, oat_class.get(), class_def_method_index);
Ian Rogers0571d352011-11-03 19:51:38 -07001643 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08001644 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001645 }
1646 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001647}
1648
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001649void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Ian Rogers0571d352011-11-03 19:51:38 -07001650 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001651 uint32_t field_idx = it.GetMemberIndex();
1652 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001653 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001654 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001655}
1656
Ian Rogers50b35e22012-10-04 10:09:15 -07001657AbstractMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
1658 const ClassDataItemIterator& it,
1659 SirtRef<Class>& klass) {
Ian Rogers19846512012-02-24 11:42:47 -08001660 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08001661 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001662 StringPiece method_name(dex_file.GetMethodName(method_id));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001663
1664 AbstractMethod* dst = NULL;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001665 if (method_name == "<init>") {
Ian Rogers50b35e22012-10-04 10:09:15 -07001666 dst = AllocConstructor(self);
Mathieu Chartier66f19252012-09-18 08:57:04 -07001667 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001668 dst = AllocMethod(self);
Elliott Hughes80609252011-09-23 17:24:51 -07001669 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001670 DCHECK(dst->IsMethod()) << PrettyDescriptor(dst->GetClass());
1671
Ian Rogers50b35e22012-10-04 10:09:15 -07001672 const char* old_cause = self->StartAssertNoThreadSuspension("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07001673 dst->SetDexMethodIndex(dex_method_idx);
1674 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001675
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001676 if (method_name == "finalize") {
1677 // Create the prototype for a signature of "()V"
1678 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1679 if (void_string_id != NULL) {
1680 const DexFile::TypeId* void_type_id =
1681 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1682 if (void_type_id != NULL) {
1683 std::vector<uint16_t> no_args;
1684 const DexFile::ProtoId* finalizer_proto =
1685 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1686 if (finalizer_proto != NULL) {
1687 // We have the prototype in the dex file
1688 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1689 klass->SetFinalizable();
1690 } else {
1691 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1692 // The Enum class declares a "final" finalize() method to prevent subclasses from
1693 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1694 // subclasses, so we exclude it here.
1695 // We also want to avoid setting the flag on Object, where we know that finalize() is
1696 // empty.
1697 if (klass_descriptor != "Ljava/lang/Object;" &&
1698 klass_descriptor != "Ljava/lang/Enum;") {
1699 klass->SetFinalizable();
1700 }
1701 }
1702 }
1703 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001704 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001705 }
Ian Rogers0571d352011-11-03 19:51:38 -07001706 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001707 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001708
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001709 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
Ian Rogers19846512012-02-24 11:42:47 -08001710 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001711 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001712 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Mathieu Chartier66f19252012-09-18 08:57:04 -07001713
1714 CHECK(dst->IsMethod());
1715
Ian Rogers50b35e22012-10-04 10:09:15 -07001716 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartier66f19252012-09-18 08:57:04 -07001717 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07001718}
1719
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001720void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001721 Thread* self = Thread::Current();
1722 SirtRef<DexCache> dex_cache(self, AllocDexCache(self, dex_file));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001723 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001724}
1725
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001726void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1727 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001728 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001729 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001730}
1731
Brian Carlstromaded5f72011-10-07 17:15:04 -07001732bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Ian Rogers50b35e22012-10-04 10:09:15 -07001733 dex_lock_.AssertHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07001734 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1735 if (dex_caches_[i]->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08001736 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001737 }
1738 }
1739 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001740}
1741
Brian Carlstromaded5f72011-10-07 17:15:04 -07001742bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Ian Rogers50b35e22012-10-04 10:09:15 -07001743 MutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001744 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001745}
1746
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001747void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001748 dex_lock_.AssertHeld(Thread::Current());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001749 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001750 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001751 dex_caches_.push_back(dex_cache.get());
Mathieu Chartier66f19252012-09-18 08:57:04 -07001752 dex_cache->SetDexFile(&dex_file);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001753}
1754
Brian Carlstromaded5f72011-10-07 17:15:04 -07001755void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07001756 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001757 {
Ian Rogers1f539342012-10-03 21:09:42 -07001758 MutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001759 if (IsDexFileRegisteredLocked(dex_file)) {
1760 return;
1761 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001762 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001763 // Don't alloc while holding the lock, since allocation may need to
1764 // suspend all threads and another thread may need the dex_lock_ to
1765 // get to a suspend point.
Ian Rogers50b35e22012-10-04 10:09:15 -07001766 SirtRef<DexCache> dex_cache(self, AllocDexCache(self, dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001767 {
Ian Rogers1f539342012-10-03 21:09:42 -07001768 MutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001769 if (IsDexFileRegisteredLocked(dex_file)) {
1770 return;
1771 }
1772 RegisterDexFileLocked(dex_file, dex_cache);
1773 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001774}
1775
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001776void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001777 MutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001778 RegisterDexFileLocked(dex_file, dex_cache);
1779}
1780
Mathieu Chartier66f19252012-09-18 08:57:04 -07001781// TODO: Remove.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001782const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001783 CHECK(dex_cache != NULL);
Mathieu Chartier66f19252012-09-18 08:57:04 -07001784 const DexFile* dex_file = dex_cache->GetDexFile();
1785 if (dex_file == NULL) {
1786 LOG(FATAL) << "DexCache has no DexFile " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001787 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001788 return *dex_file;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001789}
1790
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001791DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Ian Rogers50b35e22012-10-04 10:09:15 -07001792 MutexLock mu(Thread::Current(), dex_lock_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07001793 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1794 DexCache* dex_cache = dex_caches_[i];
1795 if (dex_cache->GetDexFile() == &dex_file) {
1796 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001797 }
1798 }
Elliott Hughes7b9d9962012-04-20 18:48:18 -07001799 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001800 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001801}
1802
Mathieu Chartier66f19252012-09-18 08:57:04 -07001803void ClassLinker::FixupDexCaches(AbstractMethod* resolution_method) const {
Ian Rogers50b35e22012-10-04 10:09:15 -07001804 MutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08001805 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1806 dex_caches_[i]->Fixup(resolution_method);
1807 }
1808}
1809
Ian Rogersc8982582012-09-07 16:53:25 -07001810Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class, Primitive::Type type) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001811 CHECK(primitive_class != NULL);
Ian Rogers1f539342012-10-03 21:09:42 -07001812 // Must hold lock on object when initializing.
1813 ObjectLock lock(Thread::Current(), primitive_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001814 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001815 primitive_class->SetPrimitiveType(type);
1816 primitive_class->SetStatus(Class::kStatusInitialized);
Ian Rogersc8982582012-09-07 16:53:25 -07001817 Class* existing = InsertClass(Primitive::Descriptor(type), primitive_class, false);
1818 CHECK(existing == NULL) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001819 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001820}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001821
Brian Carlstrombe977852011-07-19 14:54:54 -07001822// Create an array class (i.e. the class object for the array, not the
1823// array itself). "descriptor" looks like "[C" or "[[[[B" or
1824// "[Ljava/lang/String;".
1825//
1826// If "descriptor" refers to an array of primitives, look up the
1827// primitive type's internally-generated class object.
1828//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001829// "class_loader" is the class loader of the class that's referring to
1830// us. It's used to ensure that we're looking for the element type in
1831// the right context. It does NOT become the class loader for the
1832// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001833//
1834// Returns NULL with an exception raised on failure.
Ian Rogers365c1022012-06-22 15:05:28 -07001835Class* ClassLinker::CreateArrayClass(const std::string& descriptor, ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001836 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001837
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001838 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001839 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001840 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001841 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001842 return NULL;
1843 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001844
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001845 // See if the component type is already loaded. Array classes are
1846 // always associated with the class loader of their underlying
1847 // element type -- an array of Strings goes with the loader for
1848 // java/lang/String -- so we need to look for it there. (The
1849 // caller should have checked for the existence of the class
1850 // before calling here, but they did so with *their* class loader,
1851 // not the component type's loader.)
1852 //
1853 // If we find it, the caller adds "loader" to the class' initiating
1854 // loader list, which should prevent us from going through this again.
1855 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001856 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001857 // are the same, because our caller (FindClass) just did the
1858 // lookup. (Even if we get this wrong we still have correct behavior,
1859 // because we effectively do this lookup again when we add the new
1860 // class to the hash table --- necessary because of possible races with
1861 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001862 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001863 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001864 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001865 return new_class;
1866 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001867 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001868
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001869 // Fill out the fields in the Class.
1870 //
1871 // It is possible to execute some methods against arrays, because
1872 // all arrays are subclasses of java_lang_Object_, so we need to set
1873 // up a vtable. We can just point at the one in java_lang_Object_.
1874 //
1875 // Array classes are simple enough that we don't need to do a full
1876 // link step.
Ian Rogers1f539342012-10-03 21:09:42 -07001877 Thread* self = Thread::Current();
1878 SirtRef<Class> new_class(self, NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001879 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001880 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001881 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001882 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001883 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001884 new_class.reset(GetClassRoot(kObjectArrayClass));
Ian Rogers23435d02012-09-24 11:23:12 -07001885 } else if (descriptor == "[[Ljava/lang/Object;") {
1886 new_class.reset(GetClassRoot(kObjectArrayArrayClass));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001887 } else if (descriptor == class_roots_descriptors_[kJavaLangStringArrayClass]) {
1888 new_class.reset(GetClassRoot(kJavaLangStringArrayClass));
1889 } else if (descriptor == class_roots_descriptors_[kJavaLangReflectFieldArrayClass]) {
1890 new_class.reset(GetClassRoot(kJavaLangReflectFieldArrayClass));
1891 } else if (descriptor == class_roots_descriptors_[kJavaLangReflectAbstractMethodArrayClass]) {
1892 new_class.reset(GetClassRoot(kJavaLangReflectAbstractMethodArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001893 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001894 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001895 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001896 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001897 }
1898 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001899 if (new_class.get() == NULL) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001900 new_class.reset(AllocClass(self, sizeof(Class)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001901 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001902 return NULL;
1903 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001904 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001905 }
Ian Rogers1f539342012-10-03 21:09:42 -07001906 ObjectLock lock(self, new_class.get()); // Must hold lock on object when initializing.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001907 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001908 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001909 new_class->SetSuperClass(java_lang_Object);
1910 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001911 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001912 new_class->SetClassLoader(component_type->GetClassLoader());
1913 new_class->SetStatus(Class::kStatusInitialized);
1914 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001915 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001916
1917
1918 // All arrays have java/lang/Cloneable and java/io/Serializable as
1919 // interfaces. We need to set that up here, so that stuff like
1920 // "instanceof" works right.
1921 //
1922 // Note: The GC could run during the call to FindSystemClass,
1923 // so we need to make sure the class object is GC-valid while we're in
1924 // there. Do this by clearing the interface list so the GC will just
1925 // think that the entries are null.
1926
1927
1928 // Use the single, global copies of "interfaces" and "iftable"
1929 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001930 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001931 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001932
1933 // Inherit access flags from the component type. Arrays can't be
1934 // used as a superclass or interface, so we want to add "final"
1935 // and remove "interface".
1936 //
1937 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001938 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001939 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001940 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1941 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001942
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001943 Class* existing = InsertClass(descriptor, new_class.get(), false);
1944 if (existing == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001945 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001946 }
1947 // Another thread must have loaded the class after we
1948 // started but before we finished. Abandon what we've
1949 // done.
1950 //
1951 // (Yes, this happens.)
1952
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001953 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001954}
1955
1956Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001957 switch (Primitive::GetType(type)) {
1958 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001959 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001960 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001961 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001962 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001963 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001964 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001965 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001966 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001967 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001968 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001969 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001970 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001971 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001972 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001973 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001974 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001975 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001976 case Primitive::kPrimNot:
1977 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001978 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001979 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001980 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001981 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001982}
1983
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001984Class* ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001985 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001986 DexCache* dex_cache = klass->GetDexCache();
1987 std::string source;
1988 if (dex_cache != NULL) {
1989 source += " from ";
1990 source += dex_cache->GetLocation()->ToModifiedUtf8();
1991 }
1992 LOG(INFO) << "Loaded class " << descriptor << source;
1993 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001994 size_t hash = StringPieceHash()(descriptor);
Ian Rogers50b35e22012-10-04 10:09:15 -07001995 MutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001996 Table& classes = image_class ? image_classes_ : classes_;
Elliott Hughesf8349362012-06-18 15:00:06 -07001997 Class* existing = LookupClassLocked(descriptor.data(), klass->GetClassLoader(), hash, classes);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001998#ifndef NDEBUG
1999 // Check we don't have the class in the other table in error
2000 Table& other_classes = image_class ? classes_ : image_classes_;
Elliott Hughesf8349362012-06-18 15:00:06 -07002001 CHECK(LookupClassLocked(descriptor.data(), klass->GetClassLoader(), hash, other_classes) == NULL);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002002#endif
2003 if (existing != NULL) {
2004 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07002005 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002006 classes.insert(std::make_pair(hash, klass));
2007 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002008}
2009
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002010bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
2011 size_t hash = Hash(descriptor);
Ian Rogers50b35e22012-10-04 10:09:15 -07002012 MutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Elliott Hughese5448b52012-01-18 16:44:06 -08002013 typedef Table::iterator It; // TODO: C++0x auto
Brian Carlstromae826982011-11-09 01:33:42 -08002014 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002015 ClassHelper kh;
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002016 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08002017 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002018 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002019 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08002020 classes_.erase(it);
2021 return true;
2022 }
2023 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002024 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08002025 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002026 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002027 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08002028 image_classes_.erase(it);
2029 return true;
2030 }
2031 }
2032 return false;
2033}
2034
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002035Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
2036 size_t hash = Hash(descriptor);
Ian Rogers50b35e22012-10-04 10:09:15 -07002037 MutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07002038 // TODO: determine if its better to search classes_ or image_classes_ first
Elliott Hughesf8349362012-06-18 15:00:06 -07002039 Class* klass = LookupClassLocked(descriptor, class_loader, hash, classes_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002040 if (klass != NULL) {
2041 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002042 }
Elliott Hughesf8349362012-06-18 15:00:06 -07002043 return LookupClassLocked(descriptor, class_loader, hash, image_classes_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002044}
2045
Elliott Hughesf8349362012-06-18 15:00:06 -07002046Class* ClassLinker::LookupClassLocked(const char* descriptor, const ClassLoader* class_loader,
2047 size_t hash, const Table& classes) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002048 ClassHelper kh(NULL, this);
2049 typedef Table::const_iterator It; // TODO: C++0x auto
2050 for (It it = classes.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers5d76c432011-10-31 21:42:49 -07002051 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002052 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002053 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002054#ifndef NDEBUG
2055 for (++it; it != end && it->first == hash; ++it) {
Ian Rogersd85016c2012-02-03 18:27:34 -08002056 Class* klass2 = it->second;
2057 kh.ChangeClass(klass2);
2058 CHECK(!(strcmp(descriptor, kh.GetDescriptor()) == 0 && klass2->GetClassLoader() == class_loader))
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002059 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
Ian Rogersd85016c2012-02-03 18:27:34 -08002060 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002061 }
2062#endif
Ian Rogers5d76c432011-10-31 21:42:49 -07002063 return klass;
2064 }
2065 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002066 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002067}
2068
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002069void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002070 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002071 size_t hash = Hash(descriptor);
Ian Rogers50b35e22012-10-04 10:09:15 -07002072 MutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002073 typedef Table::const_iterator It; // TODO: C++0x auto
2074 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002075 ClassHelper kh(NULL, this);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002076 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002077 Class* klass = it->second;
2078 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002079 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002080 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002081 }
2082 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002083 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002084 Class* klass = it->second;
2085 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002086 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002087 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002088 }
2089 }
2090}
2091
jeffhao98eacac2011-09-14 16:11:53 -07002092void ClassLinker::VerifyClass(Class* klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002093 // TODO: assert that the monitor on the Class is held
Ian Rogers1f539342012-10-03 21:09:42 -07002094 Thread* self = Thread::Current();
2095 ObjectLock lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08002096
Ian Rogers9ffb0392012-09-10 11:56:50 -07002097 // Don't attempt to re-verify if already sufficiently verified.
2098 if (klass->IsVerified() ||
2099 (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler())) {
jeffhao98eacac2011-09-14 16:11:53 -07002100 return;
2101 }
2102
Ian Rogers9ffb0392012-09-10 11:56:50 -07002103 // The class might already be erroneous, for example at compile time if we attempted to verify
2104 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002105 if (klass->IsErroneous()) {
2106 ThrowEarlierClassFailure(klass);
2107 return;
2108 }
2109
Ian Rogers9ffb0392012-09-10 11:56:50 -07002110 if (klass->GetStatus() == Class::kStatusResolved) {
2111 klass->SetStatus(Class::kStatusVerifying);
2112 } else {
2113 CHECK_EQ(klass->GetStatus(), Class::kStatusRetryVerificationAtRuntime) << PrettyClass(klass);
2114 CHECK(!Runtime::Current()->IsCompiler());
2115 klass->SetStatus(Class::kStatusVerifyingAtRuntime);
2116 }
jeffhao98eacac2011-09-14 16:11:53 -07002117
Ian Rogers9ffb0392012-09-10 11:56:50 -07002118 // Verify super class.
Ian Rogers1c5eb702012-02-01 09:18:34 -08002119 Class* super = klass->GetSuperClass();
2120 std::string error_msg;
2121 if (super != NULL) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07002122 // Acquire lock to prevent races on verifying the super class.
Ian Rogers1f539342012-10-03 21:09:42 -07002123 ObjectLock lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002124
2125 if (!super->IsVerified() && !super->IsErroneous()) {
2126 Runtime::Current()->GetClassLinker()->VerifyClass(super);
2127 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002128 if (!super->IsCompileTimeVerified()) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08002129 error_msg = "Rejecting class ";
2130 error_msg += PrettyDescriptor(klass);
2131 error_msg += " that attempts to sub-class erroneous class ";
2132 error_msg += PrettyDescriptor(super);
2133 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Ian Rogers1f539342012-10-03 21:09:42 -07002134 SirtRef<Throwable> cause(self, self->GetException());
Ian Rogers1c5eb702012-02-01 09:18:34 -08002135 if (cause.get() != NULL) {
2136 self->ClearException();
2137 }
2138 self->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
2139 if (cause.get() != NULL) {
2140 self->GetException()->SetCause(cause.get());
2141 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08002142 klass->SetStatus(Class::kStatusError);
2143 return;
2144 }
2145 }
2146
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002147 // Try to use verification information from the oat file, otherwise do runtime verification.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002148 const DexFile& dex_file = FindDexFile(klass->GetDexCache());
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002149 Class::Status oat_file_class_status(Class::kStatusNotReady);
2150 bool preverified = VerifyClassUsingOatFile(dex_file, klass, oat_file_class_status);
jeffhaof1e6b7c2012-06-05 18:33:30 -07002151 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
jeffhaoec014232012-09-05 10:42:25 -07002152 if (oat_file_class_status == Class::kStatusError) {
2153 LOG(WARNING) << "Skipping runtime verification of erroneous class " << PrettyDescriptor(klass)
2154 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
2155 error_msg = "Rejecting class ";
2156 error_msg += PrettyDescriptor(klass);
2157 error_msg += " because it failed compile-time verification";
2158 Thread::Current()->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
2159 klass->SetStatus(Class::kStatusError);
2160 return;
2161 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002162 if (!preverified) {
2163 verifier_failure = verifier::MethodVerifier::VerifyClass(klass, error_msg);
2164 }
2165 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07002166 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
2167 LOG(WARNING) << "Soft verification failure in class " << PrettyDescriptor(klass)
2168 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2169 << " because: " << error_msg;
2170 }
Ian Rogers1f539342012-10-03 21:09:42 -07002171 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002172 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002173 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002174 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
2175 klass->SetStatus(Class::kStatusVerified);
2176 } else {
2177 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
2178 // Soft failures at compile time should be retried at runtime. Soft
2179 // failures at runtime will be handled by slow paths in the generated
2180 // code. Set status accordingly.
2181 if (Runtime::Current()->IsCompiler()) {
2182 klass->SetStatus(Class::kStatusRetryVerificationAtRuntime);
2183 } else {
2184 klass->SetStatus(Class::kStatusVerified);
2185 }
2186 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07002187 } else {
Ian Rogers09f6b562012-01-31 21:58:52 -08002188 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass)
Ian Rogers1c5eb702012-02-01 09:18:34 -08002189 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2190 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002191 self->AssertNoPendingException();
Ian Rogers1c5eb702012-02-01 09:18:34 -08002192 self->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002193 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07002194 }
jeffhao98eacac2011-09-14 16:11:53 -07002195}
2196
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002197bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, Class* klass,
2198 Class::Status& oat_file_class_status) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002199 if (!Runtime::Current()->IsStarted()) {
2200 return false;
2201 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002202 if (Runtime::Current()->UseCompileTimeClassPath()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002203 return false;
2204 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002205 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
2206 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002207 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002208 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002209 const char* descriptor = ClassHelper(klass).GetDescriptor();
2210 uint32_t class_def_index;
2211 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002212 CHECK(found) << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002213 UniquePtr<const OatFile::OatClass> oat_class(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002214 CHECK(oat_class.get() != NULL)
2215 << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002216 oat_file_class_status = oat_class->GetStatus();
Ian Rogers9ffb0392012-09-10 11:56:50 -07002217 if (oat_file_class_status == Class::kStatusVerified ||
2218 oat_file_class_status == Class::kStatusInitialized) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002219 return true;
2220 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002221 if (oat_file_class_status == Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07002222 // Compile time verification failed with a soft error. Compile time verification can fail
2223 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08002224 // class ... {
2225 // Foo x;
2226 // .... () {
2227 // if (...) {
2228 // v1 gets assigned a type of resolved class Foo
2229 // } else {
2230 // v1 gets assigned a type of unresolved class Bar
2231 // }
2232 // iput x = v1
2233 // } }
2234 // when we merge v1 following the if-the-else it results in Conflict
2235 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
2236 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
2237 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
2238 // at compile time).
2239 return false;
2240 }
jeffhao1ac29442012-03-26 11:37:32 -07002241 if (oat_file_class_status == Class::kStatusError) {
2242 // Compile time verification failed with a hard error. This is caused by invalid instructions
2243 // in the class. These errors are unrecoverable.
2244 return false;
2245 }
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002246 if (oat_file_class_status == Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08002247 // Status is uninitialized if we couldn't determine the status at compile time, for example,
2248 // not loading the class.
2249 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
2250 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002251 return false;
2252 }
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002253 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002254 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
2255
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002256 return false;
2257}
2258
2259void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, Class* klass) {
2260 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
2261 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
2262 }
2263 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
2264 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
2265 }
2266}
2267
Mathieu Chartier66f19252012-09-18 08:57:04 -07002268void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, AbstractMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002269 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
2270 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
2271 if (code_item == NULL) {
2272 return; // native or abstract method
2273 }
2274 if (code_item->tries_size_ == 0) {
2275 return; // nothing to process
2276 }
2277 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
2278 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2279 ClassLinker* linker = Runtime::Current()->GetClassLinker();
2280 for (uint32_t idx = 0; idx < handlers_size; idx++) {
2281 CatchHandlerIterator iterator(handlers_ptr);
2282 for (; iterator.HasNext(); iterator.Next()) {
2283 // Ensure exception types are resolved so that they don't need resolution to be delivered,
2284 // unresolved exception types will be ignored by exception delivery
2285 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
2286 Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
2287 if (exception_type == NULL) {
2288 DCHECK(Thread::Current()->IsExceptionPending());
2289 Thread::Current()->ClearException();
2290 }
2291 }
2292 }
2293 handlers_ptr = iterator.EndDataPointer();
2294 }
2295}
2296
Mathieu Chartier66f19252012-09-18 08:57:04 -07002297static void CheckProxyConstructor(AbstractMethod* constructor);
2298static void CheckProxyMethod(AbstractMethod* method, SirtRef<AbstractMethod>& prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08002299
Jesse Wilson95caa792011-10-12 18:14:17 -04002300Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Mathieu Chartier66f19252012-09-18 08:57:04 -07002301 ClassLoader* loader, ObjectArray<AbstractMethod>* methods,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002302 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogers1f539342012-10-03 21:09:42 -07002303 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002304 SirtRef<Class> klass(self, AllocClass(self, GetClassRoot(kJavaLangClass),
2305 sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002306 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08002307 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04002308 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002309 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002310 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002311 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002312 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07002313 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002314 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08002315
2316 klass->SetStatus(Class::kStatusIdx);
2317
2318 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
2319
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002320 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogers50b35e22012-10-04 10:09:15 -07002321 klass->SetSFields(AllocObjectArray<Field>(self, 2));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002322 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
2323 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Ian Rogers50b35e22012-10-04 10:09:15 -07002324 SirtRef<Field> interfaces_sfield(self, AllocField(self));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002325 klass->SetStaticField(0, interfaces_sfield.get());
2326 interfaces_sfield->SetDexFieldIndex(0);
2327 interfaces_sfield->SetDeclaringClass(klass.get());
2328 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
2329 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Ian Rogers50b35e22012-10-04 10:09:15 -07002330 SirtRef<Field> throws_sfield(self, AllocField(self));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002331 klass->SetStaticField(1, throws_sfield.get());
2332 throws_sfield->SetDexFieldIndex(1);
2333 throws_sfield->SetDeclaringClass(klass.get());
2334 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002335
Ian Rogers466bb252011-10-14 03:29:56 -07002336 // Proxies have 1 direct method, the constructor
Ian Rogers50b35e22012-10-04 10:09:15 -07002337 klass->SetDirectMethods(AllocObjectArray<AbstractMethod>(self, 1));
2338 klass->SetDirectMethod(0, CreateProxyConstructor(self, klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04002339
Ian Rogers466bb252011-10-14 03:29:56 -07002340 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04002341 size_t num_virtual_methods = methods->GetLength();
Ian Rogers50b35e22012-10-04 10:09:15 -07002342 klass->SetVirtualMethods(AllocObjectArray<AbstractMethod>(self, num_virtual_methods));
Jesse Wilson95caa792011-10-12 18:14:17 -04002343 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers1f539342012-10-03 21:09:42 -07002344 SirtRef<AbstractMethod> prototype(self, methods->Get(i));
Ian Rogers50b35e22012-10-04 10:09:15 -07002345 klass->SetVirtualMethod(i, CreateProxyMethod(self, klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04002346 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002347
2348 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
2349 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
2350 DCHECK(!Thread::Current()->IsExceptionPending());
2351
2352 // Link the fields and virtual methods, creating vtable and iftables
2353 if (!LinkClass(klass, interfaces)) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002354 klass->SetStatus(Class::kStatusError);
Jesse Wilson95caa792011-10-12 18:14:17 -04002355 return NULL;
2356 }
Ian Rogersc8982582012-09-07 16:53:25 -07002357 {
Ian Rogers1f539342012-10-03 21:09:42 -07002358 ObjectLock lock(self, klass.get()); // Must hold lock on object when initializing.
Ian Rogersc8982582012-09-07 16:53:25 -07002359 interfaces_sfield->SetObject(NULL, interfaces);
2360 throws_sfield->SetObject(NULL, throws);
2361 klass->SetStatus(Class::kStatusInitialized);
2362 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002363
2364 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07002365 if (kIsDebugBuild) {
Ian Rogersc2b44472011-12-14 21:17:17 -08002366 CHECK(klass->GetIFields() == NULL);
2367 CheckProxyConstructor(klass->GetDirectMethod(0));
2368 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers1f539342012-10-03 21:09:42 -07002369 SirtRef<AbstractMethod> prototype(self, methods->Get(i));
Ian Rogersc2b44472011-12-14 21:17:17 -08002370 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
2371 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002372
2373 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
2374 name->ToModifiedUtf8().c_str()));
2375 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
2376
2377 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
2378 name->ToModifiedUtf8().c_str()));
2379 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08002380
2381 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002382 CHECK_EQ(synth_proxy_class->GetInterfaces(), interfaces);
Ian Rogersc2b44472011-12-14 21:17:17 -08002383 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
2384 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002385 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04002386}
2387
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002388std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
2389 DCHECK(proxy_class->IsProxyClass());
2390 String* name = proxy_class->GetName();
2391 DCHECK(name != NULL);
2392 return DotToDescriptor(name->ToModifiedUtf8().c_str());
2393}
2394
Mathieu Chartier66f19252012-09-18 08:57:04 -07002395AbstractMethod* ClassLinker::FindMethodForProxy(const Class* proxy_class, const AbstractMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08002396 DCHECK(proxy_class->IsProxyClass());
2397 DCHECK(proxy_method->IsProxyMethod());
2398 // Locate the dex cache of the original interface/Object
2399 DexCache* dex_cache = NULL;
2400 {
2401 ObjectArray<Class>* resolved_types = proxy_method->GetDexCacheResolvedTypes();
Ian Rogers50b35e22012-10-04 10:09:15 -07002402 MutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08002403 for (size_t i = 0; i != dex_caches_.size(); ++i) {
2404 if (dex_caches_[i]->GetResolvedTypes() == resolved_types) {
2405 dex_cache = dex_caches_[i];
2406 break;
2407 }
2408 }
2409 }
2410 CHECK(dex_cache != NULL);
2411 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Mathieu Chartier66f19252012-09-18 08:57:04 -07002412 AbstractMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Ian Rogers16f93672012-02-14 12:29:06 -08002413 CHECK(resolved_method != NULL);
2414 return resolved_method;
2415}
2416
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002417
Ian Rogers50b35e22012-10-04 10:09:15 -07002418AbstractMethod* ClassLinker::CreateProxyConstructor(Thread* self, SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07002419 // Create constructor for Proxy that must initialize h
Mathieu Chartier66f19252012-09-18 08:57:04 -07002420 ObjectArray<AbstractMethod>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04002421 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002422 AbstractMethod* proxy_constructor = proxy_direct_methods->Get(2);
Ian Rogers466bb252011-10-14 03:29:56 -07002423 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
2424 // code_ too)
Ian Rogers50b35e22012-10-04 10:09:15 -07002425 AbstractMethod* constructor = down_cast<AbstractMethod*>(proxy_constructor->Clone(self));
Ian Rogers466bb252011-10-14 03:29:56 -07002426 // Make this constructor public and fix the class to be our Proxy version
2427 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002428 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08002429 return constructor;
2430}
2431
Mathieu Chartier66f19252012-09-18 08:57:04 -07002432static void CheckProxyConstructor(AbstractMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002433 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07002434 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002435 MethodHelper mh(constructor);
2436 CHECK_STREQ(mh.GetName(), "<init>");
Elliott Hughesba8eee12012-01-24 20:25:24 -08002437 CHECK_EQ(mh.GetSignature(), std::string("(Ljava/lang/reflect/InvocationHandler;)V"));
Ian Rogers466bb252011-10-14 03:29:56 -07002438 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04002439}
2440
Ian Rogers50b35e22012-10-04 10:09:15 -07002441AbstractMethod* ClassLinker::CreateProxyMethod(Thread* self, SirtRef<Class>& klass,
2442 SirtRef<AbstractMethod>& prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002443 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
2444 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08002445 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
2446 prototype.get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002447 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07002448 // as necessary
Ian Rogers50b35e22012-10-04 10:09:15 -07002449 AbstractMethod* method = down_cast<AbstractMethod*>(prototype->Clone(self));
Ian Rogers466bb252011-10-14 03:29:56 -07002450
2451 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
2452 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002453 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07002454 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002455
Ian Rogers466bb252011-10-14 03:29:56 -07002456 // At runtime the method looks like a reference and argument saving method, clone the code
2457 // related parameters from this method.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002458 AbstractMethod* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Ian Rogers466bb252011-10-14 03:29:56 -07002459 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
2460 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
2461 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
TDYa1275bb86012012-04-11 05:57:28 -07002462#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers466bb252011-10-14 03:29:56 -07002463 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
TDYa1275bb86012012-04-11 05:57:28 -07002464#else
Logan Chien7a2a23a2012-06-06 11:01:00 +08002465 OatFile::OatMethod oat_method = GetOatMethodFor(prototype.get());
2466 method->SetCode(oat_method.GetProxyStub());
TDYa1275bb86012012-04-11 05:57:28 -07002467#endif
Ian Rogers16f93672012-02-14 12:29:06 -08002468
Ian Rogersc2b44472011-12-14 21:17:17 -08002469 return method;
2470}
Jesse Wilson95caa792011-10-12 18:14:17 -04002471
Mathieu Chartier66f19252012-09-18 08:57:04 -07002472static void CheckProxyMethod(AbstractMethod* method, SirtRef<AbstractMethod>& prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002473 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07002474 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002475 CHECK(!prototype->IsFinal());
2476 CHECK(method->IsFinal());
2477 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08002478
2479 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
2480 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
2481 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
2482 CHECK_EQ(prototype->GetDexCacheResolvedMethods(), method->GetDexCacheResolvedMethods());
2483 CHECK_EQ(prototype->GetDexCacheResolvedTypes(), method->GetDexCacheResolvedTypes());
2484 CHECK_EQ(prototype->GetDexCacheInitializedStaticStorage(),
2485 method->GetDexCacheInitializedStaticStorage());
2486 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
2487
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002488 MethodHelper mh(method);
Ian Rogers19846512012-02-24 11:42:47 -08002489 MethodHelper mh2(prototype.get());
2490 CHECK_STREQ(mh.GetName(), mh2.GetName());
2491 CHECK_STREQ(mh.GetShorty(), mh2.GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07002492 // More complex sanity - via dex cache
Ian Rogers19846512012-02-24 11:42:47 -08002493 CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04002494}
2495
Ian Rogers0045a292012-03-31 21:08:41 -07002496bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit, bool can_init_statics) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002497 CHECK(klass->IsResolved() || klass->IsErroneous())
Ian Rogers9ffb0392012-09-10 11:56:50 -07002498 << PrettyClass(klass) << ": state=" << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002499
Carl Shapirob5573532011-07-12 18:22:59 -07002500 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002501
Mathieu Chartier66f19252012-09-18 08:57:04 -07002502 AbstractMethod* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002503 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002504 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Ian Rogers1f539342012-10-03 21:09:42 -07002505 ObjectLock lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002506
Brian Carlstromd1422f82011-09-28 11:37:09 -07002507 if (klass->GetStatus() == Class::kStatusInitialized) {
2508 return true;
2509 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002510
Brian Carlstromd1422f82011-09-28 11:37:09 -07002511 if (klass->IsErroneous()) {
2512 ThrowEarlierClassFailure(klass);
2513 return false;
2514 }
2515
jeffhaoebe2e0f2012-06-06 15:19:40 -07002516 if (klass->GetStatus() == Class::kStatusResolved ||
2517 klass->GetStatus() == Class::kStatusRetryVerificationAtRuntime) {
jeffhao98eacac2011-09-14 16:11:53 -07002518 VerifyClass(klass);
2519 if (klass->GetStatus() != Class::kStatusVerified) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07002520 if (klass->GetStatus() == Class::kStatusError) {
2521 CHECK(self->IsExceptionPending());
2522 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002523 return false;
2524 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002525 }
2526
Brian Carlstrom25c33252011-09-18 15:58:35 -07002527 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
2528 if (clinit != NULL && !can_run_clinit) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07002529 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified) << PrettyClass(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07002530 // if the class has a <clinit> but we can't run it during compilation,
Ian Rogers1bddec32012-02-04 12:27:34 -08002531 // don't bother going to kStatusInitializing. We return false so that
2532 // sub-classes don't believe this class is initialized.
Ian Rogers19846512012-02-24 11:42:47 -08002533 // Opportunistically link non-static methods, TODO: don't initialize and dirty pages
2534 // in second pass.
Ian Rogers1bddec32012-02-04 12:27:34 -08002535 return false;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002536 }
2537
Brian Carlstromd1422f82011-09-28 11:37:09 -07002538 // If the class is kStatusInitializing, either this thread is
2539 // initializing higher up the stack or another thread has beat us
2540 // to initializing and we need to wait. Either way, this
2541 // invocation of InitializeClass will not be responsible for
2542 // running <clinit> and will return.
2543 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002544 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002545 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002546 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002547 return true;
2548 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002549 // No. That's fine. Wait for another thread to finish initializing.
2550 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002551 }
2552
2553 if (!ValidateSuperClassDescriptors(klass)) {
2554 klass->SetStatus(Class::kStatusError);
Ian Rogers3d1548d2012-09-24 14:08:03 -07002555 lock.NotifyAll();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002556 return false;
2557 }
2558
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002559 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified) << PrettyClass(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002560
Elliott Hughesdcc24742011-09-07 14:02:44 -07002561 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002562 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002563 }
2564
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002565 uint64_t t0 = NanoTime();
2566
Ian Rogers0045a292012-03-31 21:08:41 -07002567 if (!InitializeSuperClass(klass, can_run_clinit, can_init_statics)) {
Ian Rogers1bddec32012-02-04 12:27:34 -08002568 // Super class initialization failed, this can be because we can't run
2569 // super-class class initializers in which case we'll be verified.
2570 // Otherwise this class is erroneous.
2571 if (!can_run_clinit) {
2572 CHECK(klass->IsVerified());
2573 } else {
2574 CHECK(klass->IsErroneous());
2575 }
Ian Rogers3d1548d2012-09-24 14:08:03 -07002576 // Signal to any waiting threads that saw this class as initializing.
Ian Rogers1f539342012-10-03 21:09:42 -07002577 ObjectLock lock(self, klass);
Ian Rogers3d1548d2012-09-24 14:08:03 -07002578 lock.NotifyAll();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002579 return false;
2580 }
2581
Ian Rogers0045a292012-03-31 21:08:41 -07002582 bool has_static_field_initializers = InitializeStaticFields(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002583
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002584 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002585 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002586 }
2587
Ian Rogers19846512012-02-24 11:42:47 -08002588 FixupStaticTrampolines(klass);
2589
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002590 uint64_t t1 = NanoTime();
2591
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002592 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002593 {
Ian Rogers1f539342012-10-03 21:09:42 -07002594 ObjectLock lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002595
2596 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002597 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002598 klass->SetStatus(Class::kStatusError);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002599 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002600 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002601 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2602 RuntimeStats* thread_stats = self->GetStats();
2603 ++global_stats->class_init_count;
2604 ++thread_stats->class_init_count;
2605 global_stats->class_init_time_ns += (t1 - t0);
2606 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogers0045a292012-03-31 21:08:41 -07002607 // Set the class as initialized except if we can't initialize static fields and static field
2608 // initialization is necessary.
2609 if (!can_init_statics && has_static_field_initializers) {
2610 klass->SetStatus(Class::kStatusVerified); // Don't leave class in initializing state.
2611 success = false;
2612 } else {
2613 klass->SetStatus(Class::kStatusInitialized);
2614 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002615 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002616 ClassHelper kh(klass);
2617 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002618 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002619 }
2620 lock.NotifyAll();
2621 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002622 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002623}
2624
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002625bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002626 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002627 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002628 self->AssertNoPendingException();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002629 lock.Wait();
2630
2631 // When we wake up, repeat the test for init-in-progress. If
2632 // there's an exception pending (only possible if
2633 // "interruptShouldThrow" was set), bail out.
2634 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002635 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002636 klass->SetStatus(Class::kStatusError);
2637 return false;
2638 }
2639 // Spurious wakeup? Go back to waiting.
2640 if (klass->GetStatus() == Class::kStatusInitializing) {
2641 continue;
2642 }
Ian Rogers3d1548d2012-09-24 14:08:03 -07002643 if (klass->GetStatus() == Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
2644 // Compile time initialization failed.
2645 return false;
2646 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002647 if (klass->IsErroneous()) {
2648 // The caller wants an exception, but it was thrown in a
2649 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002650 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002651 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002652 return false;
2653 }
2654 if (klass->IsInitialized()) {
2655 return true;
2656 }
2657 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2658 }
2659 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2660}
2661
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002662bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2663 if (klass->IsInterface()) {
2664 return true;
2665 }
2666 // begin with the methods local to the superclass
2667 if (klass->HasSuperClass() &&
2668 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2669 const Class* super = klass->GetSuperClass();
Ian Rogers595799e2012-01-11 17:32:51 -08002670 for (int i = super->GetVTable()->GetLength() - 1; i >= 0; --i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07002671 const AbstractMethod* method = klass->GetVTable()->Get(i);
Ian Rogers595799e2012-01-11 17:32:51 -08002672 if (method != super->GetVTable()->Get(i) &&
2673 !IsSameMethodSignatureInDifferentClassContexts(method, super, klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002674 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2675 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2676 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002677 return false;
2678 }
2679 }
2680 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002681 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2682 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2683 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002684 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2685 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07002686 const AbstractMethod* method = interface_entry->GetMethodArray()->Get(j);
Ian Rogers595799e2012-01-11 17:32:51 -08002687 if (!IsSameMethodSignatureInDifferentClassContexts(method, interface,
2688 method->GetDeclaringClass())) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002689 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2690 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2691 PrettyMethod(method).c_str(),
2692 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002693 return false;
2694 }
2695 }
2696 }
2697 }
2698 return true;
2699}
2700
Ian Rogers595799e2012-01-11 17:32:51 -08002701// Returns true if classes referenced by the signature of the method are the
2702// same classes in klass1 as they are in klass2.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002703bool ClassLinker::IsSameMethodSignatureInDifferentClassContexts(const AbstractMethod* method,
Ian Rogers595799e2012-01-11 17:32:51 -08002704 const Class* klass1,
2705 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002706 if (klass1 == klass2) {
2707 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002708 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002709 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002710 const DexFile::ProtoId& proto_id =
2711 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002712 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2713 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002714 if (descriptor == NULL) {
2715 break;
2716 }
2717 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2718 // Found a non-primitive type.
Ian Rogers595799e2012-01-11 17:32:51 -08002719 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002720 return false;
2721 }
2722 }
2723 }
2724 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002725 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002726 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Ian Rogers595799e2012-01-11 17:32:51 -08002727 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002728 return false;
2729 }
2730 }
2731 return true;
2732}
2733
Ian Rogers595799e2012-01-11 17:32:51 -08002734// Returns true if the descriptor resolves to the same class in the context of klass1 and klass2.
2735bool ClassLinker::IsSameDescriptorInDifferentClassContexts(const char* descriptor,
2736 const Class* klass1,
2737 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002738 CHECK(descriptor != NULL);
2739 CHECK(klass1 != NULL);
2740 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002741 if (klass1 == klass2) {
2742 return true;
2743 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002744 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Ian Rogers595799e2012-01-11 17:32:51 -08002745 if (found1 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002746 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002747 }
Ian Rogers595799e2012-01-11 17:32:51 -08002748 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
2749 if (found2 == NULL) {
2750 Thread::Current()->ClearException();
2751 }
2752 return found1 == found2;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002753}
2754
Ian Rogers0045a292012-03-31 21:08:41 -07002755bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit, bool can_init_fields) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002756 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002757 if (!klass->IsInterface() && klass->HasSuperClass()) {
2758 Class* super_class = klass->GetSuperClass();
Ian Rogers9ffb0392012-09-10 11:56:50 -07002759 if (!super_class->IsInitialized()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002760 CHECK(!super_class->IsInterface());
Ian Rogers1f539342012-10-03 21:09:42 -07002761 // Must hold lock on object when initializing and setting status.
2762 ObjectLock lock(Thread::Current(), klass);
Ian Rogers0045a292012-03-31 21:08:41 -07002763 bool super_initialized = InitializeClass(super_class, can_run_clinit, can_init_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002764 // TODO: check for a pending exception
2765 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002766 if (!can_run_clinit) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002767 // Don't set status to error when we can't run <clinit>.
2768 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing) << PrettyClass(klass);
2769 klass->SetStatus(Class::kStatusVerified);
2770 return false;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002771 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002772 klass->SetStatus(Class::kStatusError);
2773 klass->NotifyAll();
2774 return false;
2775 }
2776 }
2777 }
2778 return true;
2779}
2780
Ian Rogers0045a292012-03-31 21:08:41 -07002781bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit, bool can_init_fields) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002782 CHECK(c != NULL);
2783 if (c->IsInitialized()) {
2784 return true;
2785 }
2786
Elliott Hughes5f791332011-09-15 17:45:30 -07002787 Thread* self = Thread::Current();
Elliott Hughes34e06962012-04-09 13:55:55 -07002788 ScopedThreadStateChange tsc(self, kRunnable);
Ian Rogers0045a292012-03-31 21:08:41 -07002789 bool success = InitializeClass(c, can_run_clinit, can_init_fields);
Ian Rogers595799e2012-01-11 17:32:51 -08002790 if (!success) {
Ian Rogers1bddec32012-02-04 12:27:34 -08002791 CHECK(self->IsExceptionPending() || !can_run_clinit) << PrettyClass(c);
Ian Rogers595799e2012-01-11 17:32:51 -08002792 }
2793 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002794}
2795
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002796void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Elliott Hughesa0e18062012-04-13 15:59:59 -07002797 Class* c, SafeMap<uint32_t, Field*>& field_map) {
Ian Rogers365c1022012-06-22 15:05:28 -07002798 ClassLoader* cl = c->GetClassLoader();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002799 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002800 ClassDataItemIterator it(dex_file, class_data);
2801 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002802 field_map.Put(i, ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true));
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002803 }
2804}
2805
Ian Rogers0045a292012-03-31 21:08:41 -07002806bool ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002807 size_t num_static_fields = klass->NumStaticFields();
2808 if (num_static_fields == 0) {
Ian Rogers0045a292012-03-31 21:08:41 -07002809 return false;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002810 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002811 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002812 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002813 if (dex_cache == NULL) {
Ian Rogers0045a292012-03-31 21:08:41 -07002814 return false;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002815 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002816 ClassHelper kh(klass);
2817 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002818 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002819 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002820 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002821
Ian Rogers0571d352011-11-03 19:51:38 -07002822 if (it.HasNext()) {
2823 // 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 -07002824 SafeMap<uint32_t, Field*> field_map;
Ian Rogers0571d352011-11-03 19:51:38 -07002825 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2826 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002827 it.ReadValueToField(field_map.Get(i));
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002828 }
Ian Rogers0045a292012-03-31 21:08:41 -07002829 return true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002830 }
Ian Rogers0045a292012-03-31 21:08:41 -07002831 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002832}
2833
Ian Rogersc2b44472011-12-14 21:17:17 -08002834bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002835 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002836 if (!LinkSuperClass(klass)) {
2837 return false;
2838 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002839 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002840 return false;
2841 }
2842 if (!LinkInstanceFields(klass)) {
2843 return false;
2844 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002845 if (!LinkStaticFields(klass)) {
2846 return false;
2847 }
2848 CreateReferenceInstanceOffsets(klass);
2849 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002850 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2851 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002852 return true;
2853}
2854
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002855bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002856 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002857 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2858 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
Ian Rogerscab01012012-01-10 17:35:46 -08002859 CHECK(class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002860 uint16_t super_class_idx = class_def->superclass_idx_;
2861 if (super_class_idx != DexFile::kDexNoIndex16) {
2862 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002863 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002864 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002865 return false;
2866 }
Ian Rogersbe125a92012-01-11 15:19:49 -08002867 // Verify
2868 if (!klass->CanAccess(super_class)) {
2869 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2870 "Class %s extended by class %s is inaccessible",
2871 PrettyDescriptor(super_class).c_str(),
2872 PrettyDescriptor(klass.get()).c_str());
2873 return false;
2874 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002875 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002876 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002877 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2878 if (interfaces != NULL) {
2879 for (size_t i = 0; i < interfaces->Size(); i++) {
2880 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2881 Class* interface = ResolveType(dex_file, idx, klass.get());
2882 if (interface == NULL) {
2883 DCHECK(Thread::Current()->IsExceptionPending());
2884 return false;
2885 }
2886 // Verify
2887 if (!klass->CanAccess(interface)) {
2888 // TODO: the RI seemed to ignore this in my testing.
2889 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2890 "Interface %s implemented by class %s is inaccessible",
2891 PrettyDescriptor(interface).c_str(),
2892 PrettyDescriptor(klass.get()).c_str());
2893 return false;
2894 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002895 }
2896 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002897 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002898 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002899 return true;
2900}
2901
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002902bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002903 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002904 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002905 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002906 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002907 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002908 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002909 return false;
2910 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002911 return true;
2912 }
2913 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002914 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002915 return false;
2916 }
2917 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002918 if (super->IsFinal() || super->IsInterface()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002919 Thread* self = Thread::Current();
2920 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002921 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002922 PrettyDescriptor(super).c_str(),
2923 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002924 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002925 return false;
2926 }
2927 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002928 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002929 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002930 PrettyDescriptor(super).c_str(),
2931 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002932 return false;
2933 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002934
2935 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2936 if (super->IsFinalizable()) {
2937 klass->SetFinalizable();
2938 }
2939
Elliott Hughes2da50362011-10-10 16:57:08 -07002940 // Inherit reference flags (if any) from the superclass.
2941 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2942 if (reference_flags != 0) {
2943 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2944 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002945 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002946 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002947 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002948 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002949 return false;
2950 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002951
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002952#ifndef NDEBUG
2953 // Ensure super classes are fully resolved prior to resolving fields..
2954 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002955 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002956 super = super->GetSuperClass();
2957 }
2958#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002959 return true;
2960}
2961
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002962// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002963bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002964 if (klass->IsInterface()) {
2965 // No vtable.
2966 size_t count = klass->NumVirtualMethods();
2967 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002968 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002969 return false;
2970 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002971 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002972 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002973 }
jeffhaobdb76512011-09-07 11:43:16 -07002974 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002975 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002976 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002977 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002978 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002979 }
2980 return true;
2981}
2982
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002983bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Ian Rogers1f539342012-10-03 21:09:42 -07002984 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002985 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002986 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2987 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002988 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002989 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers1f539342012-10-03 21:09:42 -07002990 SirtRef<ObjectArray<AbstractMethod> >
Ian Rogers50b35e22012-10-04 10:09:15 -07002991 vtable(self, klass->GetSuperClass()->GetVTable()->CopyOf(self, max_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002992 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002993 MethodHelper local_mh(NULL, this);
2994 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002995 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07002996 AbstractMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002997 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002998 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002999 for (; j < actual_count; ++j) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003000 AbstractMethod* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003001 super_mh.ChangeMethod(super_method);
Elliott Hughes39717372012-07-13 16:21:23 -07003002 if (local_mh.HasSameNameAndSignature(&super_mh)) {
3003 if (klass->CanAccessMember(super_method->GetDeclaringClass(), super_method->GetAccessFlags())) {
3004 if (super_method->IsFinal()) {
3005 ThrowLinkageError("Method %s overrides final method in class %s",
3006 PrettyMethod(local_method).c_str(),
3007 super_mh.GetDeclaringClassDescriptor());
3008 return false;
3009 }
3010 vtable->Set(j, local_method);
3011 local_method->SetMethodIndex(j);
3012 break;
3013 } else {
3014 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method)
3015 << " would have incorrectly overridden the package-private method in "
3016 << PrettyDescriptor(super_mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003017 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003018 }
3019 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07003020 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003021 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003022 vtable->Set(actual_count, local_method);
3023 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003024 actual_count += 1;
3025 }
3026 }
3027 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08003028 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003029 return false;
3030 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003031 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003032 CHECK_LE(actual_count, max_count);
3033 if (actual_count < max_count) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003034 vtable.reset(vtable->CopyOf(self, actual_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003035 }
Ian Rogers30fab402012-01-23 15:43:46 -08003036 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003037 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003038 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07003039 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07003040 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07003041 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003042 return false;
3043 }
Ian Rogers1f539342012-10-03 21:09:42 -07003044 SirtRef<ObjectArray<AbstractMethod> >
Ian Rogers50b35e22012-10-04 10:09:15 -07003045 vtable(self, AllocObjectArray<AbstractMethod>(self, num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07003046 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003047 AbstractMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003048 vtable->Set(i, virtual_method);
3049 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003050 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003051 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003052 }
3053 return true;
3054}
3055
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003056bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003057 size_t super_ifcount;
3058 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003059 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003060 } else {
3061 super_ifcount = 0;
3062 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07003063 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003064 ClassHelper kh(klass.get(), this);
Ian Rogersd24e2642012-06-06 21:21:43 -07003065 uint32_t num_interfaces = interfaces == NULL ? kh.NumDirectInterfaces() : interfaces->GetLength();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003066 ifcount += num_interfaces;
3067 for (size_t i = 0; i < num_interfaces; i++) {
Ian Rogersd24e2642012-06-06 21:21:43 -07003068 Class* interface = interfaces == NULL ? kh.GetDirectInterface(i) : interfaces->Get(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003069 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003070 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07003071 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003072 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07003073 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003074 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003075 return true;
3076 }
Ian Rogers1f539342012-10-03 21:09:42 -07003077 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003078 SirtRef<ObjectArray<InterfaceEntry> > iftable(self, AllocIfTable(self, ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003079 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003080 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
3081 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogersb52b01a2012-01-12 17:01:38 -08003082 Class* super_interface = super_iftable->Get(i)->GetInterface();
Ian Rogers50b35e22012-10-04 10:09:15 -07003083 iftable->Set(i, AllocInterfaceEntry(self, super_interface));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003084 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003085 }
3086 // Flatten the interface inheritance hierarchy.
3087 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003088 for (size_t i = 0; i < num_interfaces; i++) {
Ian Rogersd24e2642012-06-06 21:21:43 -07003089 Class* interface = interfaces == NULL ? kh.GetDirectInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003090 DCHECK(interface != NULL);
3091 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003092 ClassHelper ih(interface);
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08003093 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003094 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003095 PrettyDescriptor(klass.get()).c_str(),
3096 PrettyDescriptor(ih.GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003097 return false;
3098 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08003099 // Check if interface is already in iftable
3100 bool duplicate = false;
3101 for (size_t j = 0; j < idx; j++) {
3102 Class* existing_interface = iftable->Get(j)->GetInterface();
3103 if (existing_interface == interface) {
3104 duplicate = true;
3105 break;
3106 }
3107 }
3108 if (!duplicate) {
3109 // Add this non-duplicate interface.
Ian Rogers50b35e22012-10-04 10:09:15 -07003110 iftable->Set(idx++, AllocInterfaceEntry(self, interface));
Ian Rogersb52b01a2012-01-12 17:01:38 -08003111 // Add this interface's non-duplicate super-interfaces.
3112 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
3113 Class* super_interface = interface->GetIfTable()->Get(j)->GetInterface();
3114 bool super_duplicate = false;
3115 for (size_t k = 0; k < idx; k++) {
3116 Class* existing_interface = iftable->Get(k)->GetInterface();
3117 if (existing_interface == super_interface) {
3118 super_duplicate = true;
3119 break;
3120 }
3121 }
3122 if (!super_duplicate) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003123 iftable->Set(idx++, AllocInterfaceEntry(self, super_interface));
Ian Rogersb52b01a2012-01-12 17:01:38 -08003124 }
3125 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003126 }
3127 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08003128 // Shrink iftable in case duplicates were found
3129 if (idx < ifcount) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003130 iftable.reset(iftable->CopyOf(self, idx));
Ian Rogersb52b01a2012-01-12 17:01:38 -08003131 ifcount = idx;
3132 } else {
3133 CHECK_EQ(idx, ifcount);
3134 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003135 klass->SetIfTable(iftable.get());
Elliott Hughes4681c802011-09-25 18:04:37 -07003136
3137 // If we're an interface, we don't need the vtable pointers, so we're done.
3138 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003139 return true;
3140 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07003141 std::vector<AbstractMethod*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003142 MethodHelper vtable_mh(NULL, this);
3143 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003144 for (size_t i = 0; i < ifcount; ++i) {
3145 InterfaceEntry* interface_entry = iftable->Get(i);
3146 Class* interface = interface_entry->GetInterface();
Ian Rogers50b35e22012-10-04 10:09:15 -07003147 ObjectArray<AbstractMethod>* method_array =
3148 AllocObjectArray<AbstractMethod>(self, interface->NumVirtualMethods());
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003149 interface_entry->SetMethodArray(method_array);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003150 ObjectArray<AbstractMethod>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003151 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003152 AbstractMethod* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003153 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003154 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07003155 // For each method listed in the interface's method list, find the
3156 // matching method in our class's method list. We want to favor the
3157 // subclass over the superclass, which just requires walking
3158 // back from the end of the vtable. (This only matters if the
3159 // superclass defines a private method and this class redefines
3160 // it -- otherwise it would use the same vtable slot. In .dex files
3161 // those don't end up in the virtual method table, so it shouldn't
3162 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003163 for (k = vtable->GetLength() - 1; k >= 0; --k) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003164 AbstractMethod* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003165 vtable_mh.ChangeMethod(vtable_method);
3166 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07003167 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07003168 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003169 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003170 return false;
3171 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003172 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003173 break;
3174 }
3175 }
3176 if (k < 0) {
Ian Rogers1f539342012-10-03 21:09:42 -07003177 SirtRef<AbstractMethod> miranda_method(self, NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07003178 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003179 AbstractMethod* mir_method = miranda_list[mir];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003180 vtable_mh.ChangeMethod(mir_method);
3181 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003182 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003183 break;
3184 }
3185 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003186 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07003187 // point the interface table at a phantom slot
Ian Rogers50b35e22012-10-04 10:09:15 -07003188 miranda_method.reset(down_cast<AbstractMethod*>(interface_method->Clone(self)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003189 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003190 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003191 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003192 }
3193 }
3194 }
Elliott Hughes4681c802011-09-25 18:04:37 -07003195 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07003196 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07003197 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07003198 klass->SetVirtualMethods((old_method_count == 0)
Ian Rogers50b35e22012-10-04 10:09:15 -07003199 ? AllocObjectArray<AbstractMethod>(self, new_method_count)
3200 : klass->GetVirtualMethods()->CopyOf(self, new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003201
Ian Rogers1f539342012-10-03 21:09:42 -07003202 SirtRef<ObjectArray<AbstractMethod> > vtable(self, klass->GetVTableDuringLinking());
Ian Rogers30fab402012-01-23 15:43:46 -08003203 CHECK(vtable.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003204 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07003205 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers50b35e22012-10-04 10:09:15 -07003206 vtable.reset(vtable->CopyOf(self, new_vtable_count));
Elliott Hughes4681c802011-09-25 18:04:37 -07003207 for (size_t i = 0; i < miranda_list.size(); ++i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003208 AbstractMethod* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07003209 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07003210 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
3211 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
3212 klass->SetVirtualMethod(old_method_count + i, method);
3213 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003214 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003215 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08003216 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003217 }
Elliott Hughes4681c802011-09-25 18:04:37 -07003218
Mathieu Chartier66f19252012-09-18 08:57:04 -07003219 ObjectArray<AbstractMethod>* vtable = klass->GetVTableDuringLinking();
Elliott Hughes4681c802011-09-25 18:04:37 -07003220 for (int i = 0; i < vtable->GetLength(); ++i) {
3221 CHECK(vtable->Get(i) != NULL);
3222 }
3223
3224// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
3225
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003226 return true;
3227}
3228
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003229bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
3230 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003231 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003232}
3233
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003234bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
3235 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003236 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003237 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003238 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07003239 return success;
3240}
3241
Brian Carlstromdbc05252011-09-09 01:59:59 -07003242struct LinkFieldsComparator {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003243 explicit LinkFieldsComparator(FieldHelper* fh)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003244 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003245 : fh_(fh) {}
3246 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
3247 bool operator()(const Field* field1, const Field* field2) NO_THREAD_SAFETY_ANALYSIS {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003248 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003249 fh_->ChangeField(field1);
3250 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
3251 fh_->ChangeField(field2);
3252 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003253 bool isPrimitive1 = type1 != Primitive::kPrimNot;
3254 bool isPrimitive2 = type2 != Primitive::kPrimNot;
3255 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
3256 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003257 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
3258 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
3259 if (order1 != order2) {
3260 return order1 < order2;
3261 }
3262
3263 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003264 fh_->ChangeField(field1);
3265 StringPiece name1(fh_->GetName());
3266 fh_->ChangeField(field2);
3267 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07003268 return name1 < name2;
3269 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003270
3271 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07003272};
3273
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003274bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003275 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003276 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003277
3278 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003279 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003280
3281 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07003282 size_t size;
3283 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003284 if (is_static) {
3285 size = klass->GetClassSize();
3286 field_offset = Class::FieldsOffset();
3287 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003288 Class* super_class = klass->GetSuperClass();
3289 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07003290 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003291 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003292 }
3293 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003294 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003295
Brian Carlstromdbc05252011-09-09 01:59:59 -07003296 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003297
Brian Carlstromdbc05252011-09-09 01:59:59 -07003298 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07003299 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07003300 std::deque<Field*> grouped_and_sorted_fields;
3301 for (size_t i = 0; i < num_fields; i++) {
3302 grouped_and_sorted_fields.push_back(fields->Get(i));
3303 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003304 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003305 std::sort(grouped_and_sorted_fields.begin(),
3306 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003307 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07003308
3309 // References should be at the front.
3310 size_t current_field = 0;
3311 size_t num_reference_fields = 0;
3312 for (; current_field < num_fields; current_field++) {
3313 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003314 fh.ChangeField(field);
3315 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003316 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07003317 if (isPrimitive) {
3318 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003319 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07003320 grouped_and_sorted_fields.pop_front();
3321 num_reference_fields++;
3322 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003323 field->SetOffset(field_offset);
3324 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003325 }
3326
3327 // Now we want to pack all of the double-wide fields together. If
3328 // we're not aligned, though, we want to shuffle one 32-bit field
3329 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07003330 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003331 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
3332 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003333 fh.ChangeField(field);
3334 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003335 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
3336 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003337 continue;
3338 }
3339 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003340 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003341 // drop the consumed field
3342 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
3343 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003344 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07003345 // whether we found a 32-bit field for padding or not, we advance
3346 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003347 }
3348
3349 // Alignment is good, shuffle any double-wide fields forward, and
3350 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07003351 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07003352 while (!grouped_and_sorted_fields.empty()) {
3353 Field* field = grouped_and_sorted_fields.front();
3354 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003355 fh.ChangeField(field);
3356 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003357 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07003358 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003359 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003360 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003361 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07003362 ? sizeof(uint64_t)
3363 : sizeof(uint32_t)));
3364 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003365 }
3366
Elliott Hughesadb460d2011-10-05 17:02:34 -07003367 // 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 -08003368 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
3369 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07003370 // We know there are no non-reference fields in the Reference classes, and we know
3371 // that 'referent' is alphabetically last, so this is easy...
3372 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003373 fh.ChangeField(fields->Get(num_fields - 1));
Elliott Hughesba8eee12012-01-24 20:25:24 -08003374 CHECK_STREQ(fh.GetName(), "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07003375 --num_reference_fields;
3376 }
3377
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003378#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07003379 // Make sure that all reference fields appear before
3380 // non-reference fields, and all double-wide fields are aligned.
3381 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07003382 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003383 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003384 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003385 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003386 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07003387 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07003388 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
3389 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003390 fh.ChangeField(field);
3391 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003392 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003393 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07003394 is_primitive = true; // We lied above, so we have to expect a lie here.
3395 }
3396 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07003397 if (!seen_non_ref) {
3398 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003399 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003400 }
Brian Carlstrombe977852011-07-19 14:54:54 -07003401 } else {
3402 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003403 }
3404 }
Brian Carlstrombe977852011-07-19 14:54:54 -07003405 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003406 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003407 }
3408#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003409 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003410 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003411 if (is_static) {
3412 klass->SetNumReferenceStaticFields(num_reference_fields);
3413 klass->SetClassSize(size);
3414 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003415 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003416 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003417 klass->SetObjectSize(size);
3418 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003419 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003420 return true;
3421}
3422
3423// Set the bitmap of reference offsets, refOffsets, from the ifields
3424// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003425void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003426 uint32_t reference_offsets = 0;
3427 Class* super_class = klass->GetSuperClass();
3428 if (super_class != NULL) {
3429 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003430 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003431 if (reference_offsets == CLASS_WALK_SUPER) {
3432 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003433 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003434 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003435 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003436 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003437}
3438
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003439void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003440 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003441}
3442
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003443void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003444 uint32_t reference_offsets) {
3445 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003446 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
3447 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003448 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003449 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003450 // All of the fields that contain object references are guaranteed
3451 // to be at the beginning of the fields list.
3452 for (size_t i = 0; i < num_reference_fields; ++i) {
3453 // Note that byte_offset is the offset from the beginning of
3454 // object, not the offset into instance data
3455 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003456 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003457 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
3458 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
3459 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07003460 CHECK_NE(new_bit, 0U);
3461 reference_offsets |= new_bit;
3462 } else {
3463 reference_offsets = CLASS_WALK_SUPER;
3464 break;
3465 }
3466 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003467 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003468 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003469 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003470 } else {
3471 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003472 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003473}
3474
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003475String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07003476 uint32_t string_idx, DexCache* dex_cache) {
Brian Carlstrom7d776242012-03-06 23:05:49 -08003477 DCHECK(dex_cache != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003478 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003479 if (resolved != NULL) {
3480 return resolved;
3481 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003482 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
3483 int32_t utf16_length = dex_file.GetStringLength(string_id);
3484 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07003485 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003486 dex_cache->SetResolvedString(string_idx, string);
3487 return string;
3488}
3489
3490Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003491 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003492 DexCache* dex_cache,
Ian Rogers365c1022012-06-22 15:05:28 -07003493 ClassLoader* class_loader) {
Brian Carlstrom7d776242012-03-06 23:05:49 -08003494 DCHECK(dex_cache != NULL);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003495 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003496 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07003497 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003498 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003499 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05003500 // TODO: we used to throw here if resolved's class loader was not the
3501 // boot class loader. This was to permit different classes with the
3502 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003503 dex_cache->SetResolvedType(type_idx, resolved);
3504 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08003505 CHECK(Thread::Current()->IsExceptionPending())
3506 << "Expected pending exception for failed resolution of: " << descriptor;
jeffhao8cd6dda2012-02-22 10:15:34 -08003507 // Convert a ClassNotFoundException to a NoClassDefFoundError
3508 if (Thread::Current()->GetException()->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
3509 Thread::Current()->ClearException();
3510 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
3511 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003512 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003513 }
3514 return resolved;
3515}
3516
Mathieu Chartier66f19252012-09-18 08:57:04 -07003517AbstractMethod* ClassLinker::ResolveMethod(const DexFile& dex_file,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003518 uint32_t method_idx,
3519 DexCache* dex_cache,
Ian Rogers365c1022012-06-22 15:05:28 -07003520 ClassLoader* class_loader,
Mathieu Chartier66f19252012-09-18 08:57:04 -07003521 const AbstractMethod* referrer,
Ian Rogers08f753d2012-08-24 14:35:25 -07003522 InvokeType type) {
Brian Carlstrom7d776242012-03-06 23:05:49 -08003523 DCHECK(dex_cache != NULL);
Ian Rogers08f753d2012-08-24 14:35:25 -07003524 // Check for hit in the dex cache.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003525 AbstractMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003526 if (resolved != NULL) {
3527 return resolved;
3528 }
Ian Rogers08f753d2012-08-24 14:35:25 -07003529 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003530 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3531 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
3532 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07003533 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003534 return NULL;
3535 }
Ian Rogers08f753d2012-08-24 14:35:25 -07003536 // Scan using method_idx, this saves string compares but will only hit for matching dex
3537 // caches/files.
3538 switch (type) {
3539 case kDirect: // Fall-through.
3540 case kStatic:
3541 resolved = klass->FindDirectMethod(dex_cache, method_idx);
3542 break;
3543 case kInterface:
3544 resolved = klass->FindInterfaceMethod(dex_cache, method_idx);
3545 break;
3546 case kSuper: // Fall-through.
3547 case kVirtual:
3548 resolved = klass->FindVirtualMethod(dex_cache, method_idx);
3549 break;
3550 default:
3551 LOG(FATAL) << "Unreachable - invocation type: " << type;
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003552 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003553 if (resolved == NULL) {
Ian Rogers08f753d2012-08-24 14:35:25 -07003554 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003555 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
3556 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Ian Rogers08f753d2012-08-24 14:35:25 -07003557 switch (type) {
3558 case kDirect: // Fall-through.
3559 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08003560 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07003561 break;
3562 case kInterface:
3563 resolved = klass->FindInterfaceMethod(name, signature);
3564 break;
3565 case kSuper: // Fall-through.
3566 case kVirtual:
3567 resolved = klass->FindVirtualMethod(name, signature);
3568 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003569 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003570 }
Ian Rogers08f753d2012-08-24 14:35:25 -07003571 if (resolved != NULL) {
3572 // We found a method, check for incompatible class changes.
Ian Rogers87e552d2012-08-31 15:54:48 -07003573 if (resolved->CheckIncompatibleClassChange(type)) {
3574 resolved = NULL;
Ian Rogers08f753d2012-08-24 14:35:25 -07003575 }
3576 }
3577 if (resolved != NULL) {
3578 // Be a good citizen and update the dex cache to speed subsequent calls.
3579 dex_cache->SetResolvedMethod(method_idx, resolved);
3580 return resolved;
3581 } else {
jeffhaoc0228b82012-08-29 18:15:05 -07003582 // We failed to find the method which means either an access error, an incompatible class
3583 // change, or no such method. First try to find the method among direct and virtual methods.
Ian Rogers08f753d2012-08-24 14:35:25 -07003584 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
3585 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
3586 switch (type) {
3587 case kDirect:
3588 case kStatic:
3589 resolved = klass->FindVirtualMethod(name, signature);
jeffhaoc0228b82012-08-29 18:15:05 -07003590 break;
3591 case kInterface:
3592 case kVirtual:
3593 case kSuper:
3594 resolved = klass->FindDirectMethod(name, signature);
3595 break;
3596 }
3597
3598 // If we found something, check that it can be accessed by the referrer.
3599 if (resolved != NULL && referrer != NULL) {
3600 Class* methods_class = resolved->GetDeclaringClass();
3601 Class* referring_class = referrer->GetDeclaringClass();
3602 if (!referring_class->CanAccess(methods_class)) {
Ian Rogers87e552d2012-08-31 15:54:48 -07003603 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
3604 referrer, resolved, type);
jeffhaoc0228b82012-08-29 18:15:05 -07003605 return NULL;
3606 } else if (!referring_class->CanAccessMember(methods_class,
3607 resolved->GetAccessFlags())) {
Ian Rogers87e552d2012-08-31 15:54:48 -07003608 ThrowIllegalAccessErrorMethod(referring_class, resolved);
jeffhaoc0228b82012-08-29 18:15:05 -07003609 return NULL;
3610 }
3611 }
3612
3613 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
3614 // methods and throw if we find the method there. If we find nothing, throw a NoSuchMethodError.
3615 switch (type) {
3616 case kDirect:
3617 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07003618 if (resolved != NULL) {
Ian Rogers2fc14272012-08-30 10:56:57 -07003619 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003620 } else {
3621 resolved = klass->FindInterfaceMethod(name, signature);
3622 if (resolved != NULL) {
Ian Rogers2fc14272012-08-30 10:56:57 -07003623 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003624 } else {
Ian Rogers2fc14272012-08-30 10:56:57 -07003625 ThrowNoSuchMethodError(type, klass, name, signature, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003626 }
3627 }
3628 break;
3629 case kInterface:
Ian Rogers08f753d2012-08-24 14:35:25 -07003630 if (resolved != NULL) {
Ian Rogers2fc14272012-08-30 10:56:57 -07003631 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003632 } else {
3633 resolved = klass->FindVirtualMethod(name, signature);
3634 if (resolved != NULL) {
Ian Rogers2fc14272012-08-30 10:56:57 -07003635 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003636 } else {
Ian Rogers2fc14272012-08-30 10:56:57 -07003637 ThrowNoSuchMethodError(type, klass, name, signature, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003638 }
3639 }
3640 break;
3641 case kSuper:
Ian Rogers2fc14272012-08-30 10:56:57 -07003642 ThrowNoSuchMethodError(type, klass, name, signature, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003643 break;
3644 case kVirtual:
Ian Rogers08f753d2012-08-24 14:35:25 -07003645 if (resolved != NULL) {
Ian Rogers2fc14272012-08-30 10:56:57 -07003646 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003647 } else {
3648 resolved = klass->FindInterfaceMethod(name, signature);
3649 if (resolved != NULL) {
Ian Rogers2fc14272012-08-30 10:56:57 -07003650 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003651 } else {
Ian Rogers2fc14272012-08-30 10:56:57 -07003652 ThrowNoSuchMethodError(type, klass, name, signature, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003653 }
3654 }
3655 break;
3656 }
3657 DCHECK(Thread::Current()->IsExceptionPending());
3658 return NULL;
3659 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003660}
3661
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003662Field* ClassLinker::ResolveField(const DexFile& dex_file,
3663 uint32_t field_idx,
3664 DexCache* dex_cache,
Ian Rogers365c1022012-06-22 15:05:28 -07003665 ClassLoader* class_loader,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003666 bool is_static) {
Brian Carlstrom7d776242012-03-06 23:05:49 -08003667 DCHECK(dex_cache != NULL);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003668 Field* resolved = dex_cache->GetResolvedField(field_idx);
3669 if (resolved != NULL) {
3670 return resolved;
3671 }
3672 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3673 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3674 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003675 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003676 return NULL;
3677 }
3678
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003679 if (is_static) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003680 resolved = klass->FindStaticField(dex_cache, field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003681 } else {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003682 resolved = klass->FindInstanceField(dex_cache, field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003683 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003684
3685 if (resolved == NULL) {
3686 const char* name = dex_file.GetFieldName(field_id);
3687 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3688 if (is_static) {
3689 resolved = klass->FindStaticField(name, type);
3690 } else {
3691 resolved = klass->FindInstanceField(name, type);
3692 }
3693 if (resolved == NULL) {
3694 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
3695 return NULL;
3696 }
Ian Rogersb067ac22011-12-13 18:05:09 -08003697 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003698 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08003699 return resolved;
3700}
3701
3702Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
3703 uint32_t field_idx,
3704 DexCache* dex_cache,
Ian Rogers365c1022012-06-22 15:05:28 -07003705 ClassLoader* class_loader) {
Brian Carlstrom7d776242012-03-06 23:05:49 -08003706 DCHECK(dex_cache != NULL);
Ian Rogersb067ac22011-12-13 18:05:09 -08003707 Field* resolved = dex_cache->GetResolvedField(field_idx);
3708 if (resolved != NULL) {
3709 return resolved;
3710 }
3711 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3712 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3713 if (klass == NULL) {
3714 DCHECK(Thread::Current()->IsExceptionPending());
3715 return NULL;
3716 }
3717
3718 const char* name = dex_file.GetFieldName(field_id);
3719 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3720 resolved = klass->FindField(name, type);
3721 if (resolved != NULL) {
3722 dex_cache->SetResolvedField(field_idx, resolved);
3723 } else {
3724 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003725 }
3726 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07003727}
3728
Mathieu Chartier66f19252012-09-18 08:57:04 -07003729const char* ClassLinker::MethodShorty(uint32_t method_idx, AbstractMethod* referrer, uint32_t* length) {
Ian Rogersad25ac52011-10-04 19:13:33 -07003730 Class* declaring_class = referrer->GetDeclaringClass();
3731 DexCache* dex_cache = declaring_class->GetDexCache();
3732 const DexFile& dex_file = FindDexFile(dex_cache);
3733 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08003734 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07003735}
3736
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003737void ClassLinker::DumpAllClasses(int flags) const {
3738 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3739 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3740 std::vector<Class*> all_classes;
3741 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003742 MutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003743 typedef Table::const_iterator It; // TODO: C++0x auto
3744 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3745 all_classes.push_back(it->second);
3746 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003747 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3748 all_classes.push_back(it->second);
3749 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003750 }
3751
3752 for (size_t i = 0; i < all_classes.size(); ++i) {
3753 all_classes[i]->DumpClass(std::cerr, flags);
3754 }
3755}
3756
Elliott Hughescac6cc72011-11-03 20:31:21 -07003757void ClassLinker::DumpForSigQuit(std::ostream& os) const {
Ian Rogers50b35e22012-10-04 10:09:15 -07003758 MutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Elliott Hughescac6cc72011-11-03 20:31:21 -07003759 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3760 << classes_.size() << " allocated classes\n";
3761}
3762
Elliott Hughese27955c2011-08-26 15:21:24 -07003763size_t ClassLinker::NumLoadedClasses() const {
Ian Rogers50b35e22012-10-04 10:09:15 -07003764 MutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003765 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003766}
3767
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003768pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07003769 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003770}
3771
3772pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003773 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003774}
3775
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003776void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3777 DCHECK(!init_done_);
3778
3779 DCHECK(klass != NULL);
3780 DCHECK(klass->GetClassLoader() == NULL);
3781
3782 DCHECK(class_roots_ != NULL);
3783 DCHECK(class_roots_->Get(class_root) == NULL);
3784 class_roots_->Set(class_root, klass);
3785}
3786
Logan Chien0c717dd2012-03-28 18:31:07 +08003787void ClassLinker::RelocateExecutable() {
Ian Rogers50b35e22012-10-04 10:09:15 -07003788 MutexLock mu(Thread::Current(), dex_lock_);
Logan Chien0c717dd2012-03-28 18:31:07 +08003789 for (size_t i = 0; i < oat_files_.size(); ++i) {
3790 const_cast<OatFile*>(oat_files_[i])->RelocateExecutable();
3791 }
3792}
3793
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003794} // namespace art