blob: 8a655bde1c8f786f0f5235988f3de6e764fc3015 [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;",
Mathieu Chartier66f19252012-09-18 08:57:04 -0700179 "[Ljava/lang/reflect/AbstractMethod;",
Ian Rogers4445a7e2012-10-05 17:19:13 -0700180 "[Ljava/lang/reflect/Field;",
181 "[Ljava/lang/reflect/Method;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700182 "Ljava/lang/ClassLoader;",
Ian Rogers5167c972012-02-03 10:41:20 -0800183 "Ljava/lang/Throwable;",
jeffhao8cd6dda2012-02-22 10:15:34 -0800184 "Ljava/lang/ClassNotFoundException;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700185 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700186 "Z",
187 "B",
188 "C",
189 "D",
190 "F",
191 "I",
192 "J",
193 "S",
194 "V",
195 "[Z",
196 "[B",
197 "[C",
198 "[D",
199 "[F",
200 "[I",
201 "[J",
202 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700203 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700204};
205
Brian Carlstroma004aa92012-02-08 18:05:09 -0800206ClassLinker* ClassLinker::CreateFromCompiler(const std::vector<const DexFile*>& boot_class_path,
207 InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700208 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800209 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstroma004aa92012-02-08 18:05:09 -0800210 class_linker->InitFromCompiler(boot_class_path);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700211 return class_linker.release();
212}
213
Brian Carlstroma004aa92012-02-08 18:05:09 -0800214ClassLinker* ClassLinker::CreateFromImage(InternTable* intern_table) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800215 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700216 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700217 return class_linker.release();
218}
219
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800220ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700221 // dex_lock_ is recursive as it may be used in stack dumping.
222 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel, true),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700223 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700224 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700225 init_done_(false),
226 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700227 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700228}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700229
Brian Carlstroma004aa92012-02-08 18:05:09 -0800230void ClassLinker::InitFromCompiler(const std::vector<const DexFile*>& boot_class_path) {
231 VLOG(startup) << "ClassLinker::Init";
232 CHECK(Runtime::Current()->IsCompiler());
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700233
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700234 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700235
Elliott Hughes30646832011-10-13 16:59:46 -0700236 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700237 Thread* self = Thread::Current();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800238 Heap* heap = Runtime::Current()->GetHeap();
Ian Rogers50b35e22012-10-04 10:09:15 -0700239 SirtRef<Class>
240 java_lang_Class(self, down_cast<Class*>(heap->AllocObject(self, NULL, sizeof(ClassClass))));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700241 CHECK(java_lang_Class.get() != NULL);
242 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700243 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700244 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700245
Elliott Hughes418d20f2011-09-22 14:00:39 -0700246 // Class[] is used for reflection support.
Ian Rogers50b35e22012-10-04 10:09:15 -0700247 SirtRef<Class> class_array_class(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700248 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700249
Ian Rogers23435d02012-09-24 11:23:12 -0700250 // java_lang_Object comes next so that object_array_class can be created.
Ian Rogers50b35e22012-10-04 10:09:15 -0700251 SirtRef<Class> java_lang_Object(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700252 CHECK(java_lang_Object.get() != NULL);
Ian Rogers23435d02012-09-24 11:23:12 -0700253 // backfill Object as the super class of Class.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700254 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700255 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700256
Ian Rogers23435d02012-09-24 11:23:12 -0700257 // Object[] next to hold class roots.
Ian Rogers50b35e22012-10-04 10:09:15 -0700258 SirtRef<Class> object_array_class(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700259 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700260
Ian Rogers23435d02012-09-24 11:23:12 -0700261 // Object[][] needed for iftables.
Ian Rogers50b35e22012-10-04 10:09:15 -0700262 SirtRef<Class> object_array_array_class(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Ian Rogers23435d02012-09-24 11:23:12 -0700263 object_array_array_class->SetComponentType(object_array_class.get());
264
265 // Setup the char class to be used for char[].
Ian Rogers50b35e22012-10-04 10:09:15 -0700266 SirtRef<Class> char_class(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700267
Ian Rogers23435d02012-09-24 11:23:12 -0700268 // Setup the char[] class to be used for String.
Ian Rogers50b35e22012-10-04 10:09:15 -0700269 SirtRef<Class> char_array_class(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700270 char_array_class->SetComponentType(char_class.get());
271 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700272
Ian Rogers23435d02012-09-24 11:23:12 -0700273 // Setup String.
Ian Rogers50b35e22012-10-04 10:09:15 -0700274 SirtRef<Class> java_lang_String(self, AllocClass(self, java_lang_Class.get(), sizeof(StringClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700275 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700276 java_lang_String->SetObjectSize(sizeof(String));
277 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400278
Ian Rogers23435d02012-09-24 11:23:12 -0700279 // Create storage for root classes, save away our work so far (requires descriptors).
Ian Rogers50b35e22012-10-04 10:09:15 -0700280 class_roots_ = ObjectArray<Class>::Alloc(self, object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700281 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700282 SetClassRoot(kJavaLangClass, java_lang_Class.get());
283 SetClassRoot(kJavaLangObject, java_lang_Object.get());
284 SetClassRoot(kClassArrayClass, class_array_class.get());
285 SetClassRoot(kObjectArrayClass, object_array_class.get());
Ian Rogers23435d02012-09-24 11:23:12 -0700286 SetClassRoot(kObjectArrayArrayClass, object_array_array_class.get());
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700287 SetClassRoot(kCharArrayClass, char_array_class.get());
288 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700289
290 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700291 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
292 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
293 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
294 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
295 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
296 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
297 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
298 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700299
Ian Rogers23435d02012-09-24 11:23:12 -0700300 // Create array interface entries to populate once we can load system classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700301 array_iftable_ = AllocIfTable(self, 2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700302
Ian Rogers23435d02012-09-24 11:23:12 -0700303 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Ian Rogers50b35e22012-10-04 10:09:15 -0700304 SirtRef<Class> int_array_class(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700305 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700306 IntArray::SetArrayClass(int_array_class.get());
307 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700308
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700309 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700310
Mathieu Chartier66f19252012-09-18 08:57:04 -0700311 // Setup DexCache. This can not be done later since AppendToBootClassPath calls AllocDexCache.
Ian Rogers50b35e22012-10-04 10:09:15 -0700312 SirtRef<Class>
313 java_lang_DexCache(self, AllocClass(self, java_lang_Class.get(), sizeof(DexCacheClass)));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700314 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.get());
315 java_lang_DexCache->SetObjectSize(sizeof(DexCacheClass));
316 java_lang_DexCache->SetStatus(Class::kStatusResolved);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700317
Mathieu Chartier66f19252012-09-18 08:57:04 -0700318 // Constructor, Field, Method, and AbstractMethod are necessary so that FindClass can link members.
Ian Rogers50b35e22012-10-04 10:09:15 -0700319 SirtRef<Class> java_lang_reflect_Field(self, AllocClass(self, java_lang_Class.get(),
320 sizeof(FieldClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700321 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700322 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700323 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700324 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700325 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700326
Ian Rogers50b35e22012-10-04 10:09:15 -0700327 SirtRef<Class> java_lang_reflect_AbstractMethod(self, AllocClass(self, java_lang_Class.get(),
328 sizeof(MethodClass)));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700329 CHECK(java_lang_reflect_AbstractMethod.get() != NULL);
330 java_lang_reflect_AbstractMethod->SetObjectSize(sizeof(AbstractMethod));
331 SetClassRoot(kJavaLangReflectAbstractMethod, java_lang_reflect_AbstractMethod.get());
332 java_lang_reflect_AbstractMethod->SetStatus(Class::kStatusResolved);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700333
334 SirtRef<Class> java_lang_reflect_Constructor(self, AllocClass(self, java_lang_Class.get(),
335 sizeof(MethodClass)));
336 CHECK(java_lang_reflect_Constructor.get() != NULL);
337 java_lang_reflect_Constructor->SetObjectSize(sizeof(Constructor));
338 java_lang_reflect_Constructor->SetSuperClass(java_lang_reflect_AbstractMethod.get());
339 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
340 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
341
342 SirtRef<Class> java_lang_reflect_Method(self, AllocClass(self, java_lang_Class.get(),
343 sizeof(MethodClass)));
344 CHECK(java_lang_reflect_Method.get() != NULL);
345 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
346 java_lang_reflect_Method->SetSuperClass(java_lang_reflect_AbstractMethod.get());
347 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
348 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
349
Mathieu Chartier66f19252012-09-18 08:57:04 -0700350 AbstractMethod::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
351
352 // Set up array classes for string, field, method
Ian Rogers50b35e22012-10-04 10:09:15 -0700353 SirtRef<Class> object_array_string(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700354 object_array_string->SetComponentType(java_lang_String.get());
355 SetClassRoot(kJavaLangStringArrayClass, object_array_string.get());
356
Ian Rogers4445a7e2012-10-05 17:19:13 -0700357 SirtRef<Class> object_array_abstract_method(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
358 object_array_abstract_method->SetComponentType(java_lang_reflect_AbstractMethod.get());
359 SetClassRoot(kJavaLangReflectAbstractMethodArrayClass, object_array_abstract_method.get());
360
Ian Rogers50b35e22012-10-04 10:09:15 -0700361 SirtRef<Class> object_array_field(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700362 object_array_field->SetComponentType(java_lang_reflect_Field.get());
363 SetClassRoot(kJavaLangReflectFieldArrayClass, object_array_field.get());
364
Ian Rogers4445a7e2012-10-05 17:19:13 -0700365 SirtRef<Class> object_array_method(self, AllocClass(self, java_lang_Class.get(), sizeof(Class)));
366 object_array_method->SetComponentType(java_lang_reflect_Method.get());
367 SetClassRoot(kJavaLangReflectMethodArrayClass, object_array_method.get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700368
Ian Rogers23435d02012-09-24 11:23:12 -0700369 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
370 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
371 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700372 CHECK_NE(0U, boot_class_path.size());
373 for (size_t i = 0; i != boot_class_path.size(); ++i) {
374 const DexFile* dex_file = boot_class_path[i];
375 CHECK(dex_file != NULL);
376 AppendToBootClassPath(*dex_file);
377 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700378
379 // now we can use FindSystemClass
380
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700381 // run char class through InitializePrimitiveClass to finish init
Ian Rogersc8982582012-09-07 16:53:25 -0700382 InitializePrimitiveClass(char_class.get(), Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700383 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700384
Mathieu Chartier66f19252012-09-18 08:57:04 -0700385 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700386 java_lang_Object->SetStatus(Class::kStatusNotReady);
387 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700388 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700389 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
390 java_lang_String->SetStatus(Class::kStatusNotReady);
391 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700392 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700393 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700394 java_lang_DexCache->SetStatus(Class::kStatusNotReady);
395 Class* DexCache_class = FindSystemClass("Ljava/lang/DexCache;");
396 CHECK_EQ(java_lang_String.get(), String_class);
397 CHECK_EQ(java_lang_DexCache.get(), DexCache_class);
398 CHECK_EQ(java_lang_DexCache->GetObjectSize(), sizeof(DexCache));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700399
Ian Rogers23435d02012-09-24 11:23:12 -0700400 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700401 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
402 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
403
404 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
405 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
406
407 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700408 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700409
410 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
411 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
412
413 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700414 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700415
416 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
417 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
418
419 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
420 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
421
422 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
423 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
424
Elliott Hughes418d20f2011-09-22 14:00:39 -0700425 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700426 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700427
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700428 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700429 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700430
Ian Rogers23435d02012-09-24 11:23:12 -0700431 Class* found_object_array_array_class = FindSystemClass("[[Ljava/lang/Object;");
432 CHECK_EQ(object_array_array_class.get(), found_object_array_array_class);
433
434 // Setup the single, global copy of "iftable".
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700435 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
436 CHECK(java_lang_Cloneable != NULL);
437 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
438 CHECK(java_io_Serializable != NULL);
Ian Rogers23435d02012-09-24 11:23:12 -0700439 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
440 // crawl up and explicitly list all of the supers as well.
Ian Rogers50b35e22012-10-04 10:09:15 -0700441 array_iftable_->Set(0, AllocInterfaceEntry(self, java_lang_Cloneable));
442 array_iftable_->Set(1, AllocInterfaceEntry(self, java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700443
Ian Rogers23435d02012-09-24 11:23:12 -0700444 // Sanity check Class[] and Object[]'s interfaces.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800445 ClassHelper kh(class_array_class.get(), this);
Ian Rogersd24e2642012-06-06 21:21:43 -0700446 CHECK_EQ(java_lang_Cloneable, kh.GetDirectInterface(0));
447 CHECK_EQ(java_io_Serializable, kh.GetDirectInterface(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800448 kh.ChangeClass(object_array_class.get());
Ian Rogersd24e2642012-06-06 21:21:43 -0700449 CHECK_EQ(java_lang_Cloneable, kh.GetDirectInterface(0));
450 CHECK_EQ(java_io_Serializable, kh.GetDirectInterface(1));
Ian Rogers23435d02012-09-24 11:23:12 -0700451 // Run Class, Constructor, Field, and Method through FindSystemClass. This initializes their
452 // dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700453 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700454 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700455
Mathieu Chartier66f19252012-09-18 08:57:04 -0700456 java_lang_reflect_AbstractMethod->SetStatus(Class::kStatusNotReady);
457 Class* Abstract_method_class = FindSystemClass("Ljava/lang/reflect/AbstractMethod;");
458 CHECK_EQ(java_lang_reflect_AbstractMethod.get(), Abstract_method_class);
459
460 // Method extends AbstractMethod so must reset after.
461 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
462 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
463 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
464
465 // Constructor extends AbstractMethod so must reset after.
Elliott Hughes80609252011-09-23 17:24:51 -0700466 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
467 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700468 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700469
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700470 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700471 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700472 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700473
Mathieu Chartier66f19252012-09-18 08:57:04 -0700474 Class* String_array_class = FindSystemClass(class_roots_descriptors_[kJavaLangStringArrayClass]);
475 CHECK_EQ(object_array_string.get(), String_array_class);
476
Mathieu Chartier66f19252012-09-18 08:57:04 -0700477 Class* Abstract_method_array_class =
478 FindSystemClass(class_roots_descriptors_[kJavaLangReflectAbstractMethodArrayClass]);
479 CHECK_EQ(object_array_abstract_method.get(), Abstract_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700480
Ian Rogers4445a7e2012-10-05 17:19:13 -0700481 Class* Field_array_class = FindSystemClass(class_roots_descriptors_[kJavaLangReflectFieldArrayClass]);
482 CHECK_EQ(object_array_field.get(), Field_array_class);
483
484 Class* Method_array_class =
485 FindSystemClass(class_roots_descriptors_[kJavaLangReflectMethodArrayClass]);
486 CHECK_EQ(object_array_method.get(), Method_array_class);
487
Ian Rogers23435d02012-09-24 11:23:12 -0700488 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700489
Ian Rogers23435d02012-09-24 11:23:12 -0700490 // Create java.lang.reflect.Proxy root.
Ian Rogers466bb252011-10-14 03:29:56 -0700491 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
492 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
493
Brian Carlstrom1f870082011-08-23 16:02:11 -0700494 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700495 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
496 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700497 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700498 java_lang_ref_FinalizerReference->SetAccessFlags(
499 java_lang_ref_FinalizerReference->GetAccessFlags() |
500 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700501 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700502 java_lang_ref_PhantomReference->SetAccessFlags(
503 java_lang_ref_PhantomReference->GetAccessFlags() |
504 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700505 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700506 java_lang_ref_SoftReference->SetAccessFlags(
507 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700508 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700509 java_lang_ref_WeakReference->SetAccessFlags(
510 java_lang_ref_WeakReference->GetAccessFlags() |
511 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700512
Ian Rogers23435d02012-09-24 11:23:12 -0700513 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700514 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700515 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700516 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
517
jeffhao8cd6dda2012-02-22 10:15:34 -0800518 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700519 // java.lang.StackTraceElement as a convenience.
Ian Rogers5167c972012-02-03 10:41:20 -0800520 SetClassRoot(kJavaLangThrowable, FindSystemClass("Ljava/lang/Throwable;"));
521 Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
jeffhao8cd6dda2012-02-22 10:15:34 -0800522 SetClassRoot(kJavaLangClassNotFoundException, FindSystemClass("Ljava/lang/ClassNotFoundException;"));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700523 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
524 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700525 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700526
Brian Carlstroma663ea52011-08-19 23:33:41 -0700527 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700528
Brian Carlstroma004aa92012-02-08 18:05:09 -0800529 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700530}
531
532void ClassLinker::FinishInit() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800533 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700534
535 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700536 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700537 // as the types of the field can't be resolved prior to the runtime being
538 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700539 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700540 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700541 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
542
Ian Rogers4445a7e2012-10-05 17:19:13 -0700543 const DexFile& java_lang_dex = *java_lang_ref_Reference->GetDexCache()->GetDexFile();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800544
Brian Carlstrom16192862011-09-12 17:50:06 -0700545 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800546 FieldHelper fh(pendingNext, this);
547 CHECK_STREQ(fh.GetName(), "pendingNext");
548 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
549 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700550
551 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800552 fh.ChangeField(queue);
553 CHECK_STREQ(fh.GetName(), "queue");
554 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
555 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700556
557 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800558 fh.ChangeField(queueNext);
559 CHECK_STREQ(fh.GetName(), "queueNext");
560 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
561 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700562
563 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800564 fh.ChangeField(referent);
565 CHECK_STREQ(fh.GetName(), "referent");
566 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
567 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700568
569 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800570 fh.ChangeField(zombie);
571 CHECK_STREQ(fh.GetName(), "zombie");
572 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
573 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700574
Elliott Hughesa4f94742012-05-29 16:28:38 -0700575 Heap* heap = Runtime::Current()->GetHeap();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800576 heap->SetReferenceOffsets(referent->GetOffset(),
Brian Carlstrom16192862011-09-12 17:50:06 -0700577 queue->GetOffset(),
578 queueNext->GetOffset(),
579 pendingNext->GetOffset(),
580 zombie->GetOffset());
581
Brian Carlstroma663ea52011-08-19 23:33:41 -0700582 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700583 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700584 ClassRoot class_root = static_cast<ClassRoot>(i);
585 Class* klass = GetClassRoot(class_root);
586 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700587 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700588 // note SetClassRoot does additional validation.
589 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700590 }
591
Elliott Hughes92f14b22011-10-06 12:29:54 -0700592 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700593
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700594 // disable the slow paths in FindClass and CreatePrimitiveClass now
595 // that Object, Class, and Object[] are setup
596 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700597
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800598 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700599}
600
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700601void ClassLinker::RunRootClinits() {
602 Thread* self = Thread::Current();
603 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
604 Class* c = GetClassRoot(ClassRoot(i));
605 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Ian Rogers0045a292012-03-31 21:08:41 -0700606 EnsureInitialized(GetClassRoot(ClassRoot(i)), true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700607 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700608 }
609 }
610}
611
Brian Carlstromd601af82012-01-06 10:15:19 -0800612bool ClassLinker::GenerateOatFile(const std::string& dex_filename,
613 int oat_fd,
614 const std::string& oat_cache_filename) {
Brian Carlstroma56fcd62012-02-04 21:23:01 -0800615 std::string dex2oat_string(GetAndroidRoot());
Elliott Hughes67d92002012-03-26 15:08:51 -0700616 dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800617 const char* dex2oat = dex2oat_string.c_str();
618
Brian Carlstroma004aa92012-02-08 18:05:09 -0800619 const char* class_path = Runtime::Current()->GetClassPathString().c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800620
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800621 Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800622 std::string boot_image_option_string("--boot-image=");
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700623 boot_image_option_string += heap->GetImageSpace()->GetImageFilename();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800624 const char* boot_image_option = boot_image_option_string.c_str();
625
626 std::string dex_file_option_string("--dex-file=");
Brian Carlstromd601af82012-01-06 10:15:19 -0800627 dex_file_option_string += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800628 const char* dex_file_option = dex_file_option_string.c_str();
629
Brian Carlstromd601af82012-01-06 10:15:19 -0800630 std::string oat_fd_option_string("--oat-fd=");
Brian Carlstrom866c8622012-01-06 16:35:13 -0800631 StringAppendF(&oat_fd_option_string, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800632 const char* oat_fd_option = oat_fd_option_string.c_str();
633
Brian Carlstroma004aa92012-02-08 18:05:09 -0800634 std::string oat_location_option_string("--oat-location=");
635 oat_location_option_string += oat_cache_filename;
636 const char* oat_location_option = oat_location_option_string.c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800637
jeffhao262bf462011-10-20 18:36:32 -0700638 // fork and exec dex2oat
639 pid_t pid = fork();
640 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800641 // no allocation allowed between fork and exec
Ian Rogers725aee52012-01-11 11:56:56 -0800642
643 // change process groups, so we don't get reaped by ProcessManager
644 setpgid(0, 0);
645
jeffhao10037c82012-01-23 15:06:23 -0800646 VLOG(class_linker) << dex2oat
647 << " --runtime-arg -Xms64m"
648 << " --runtime-arg -Xmx64m"
649 << " --runtime-arg -classpath"
650 << " --runtime-arg " << class_path
651 << " " << boot_image_option
652 << " " << dex_file_option
653 << " " << oat_fd_option
Brian Carlstroma004aa92012-02-08 18:05:09 -0800654 << " " << oat_location_option;
jeffhao10037c82012-01-23 15:06:23 -0800655
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800656 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700657 "--runtime-arg", "-Xms64m",
658 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500659 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800660 "--runtime-arg", class_path,
661 boot_image_option,
662 dex_file_option,
Brian Carlstromd601af82012-01-06 10:15:19 -0800663 oat_fd_option,
Brian Carlstroma004aa92012-02-08 18:05:09 -0800664 oat_location_option,
jeffhao262bf462011-10-20 18:36:32 -0700665 NULL);
666
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800667 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
Brian Carlstromd601af82012-01-06 10:15:19 -0800668 return false;
jeffhao262bf462011-10-20 18:36:32 -0700669 } else {
670 // wait for dex2oat to finish
671 int status;
672 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
673 if (got_pid != pid) {
674 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
Brian Carlstromd601af82012-01-06 10:15:19 -0800675 return false;
jeffhao262bf462011-10-20 18:36:32 -0700676 }
677 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800678 LOG(ERROR) << dex2oat << " failed with dex-file=" << dex_filename;
679 return false;
jeffhao262bf462011-10-20 18:36:32 -0700680 }
681 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800682 return true;
jeffhao262bf462011-10-20 18:36:32 -0700683}
684
Brian Carlstrom866c8622012-01-06 16:35:13 -0800685void ClassLinker::RegisterOatFile(const OatFile& oat_file) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700686 MutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800687 RegisterOatFileLocked(oat_file);
688}
689
690void ClassLinker::RegisterOatFileLocked(const OatFile& oat_file) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700691 dex_lock_.AssertHeld(Thread::Current());
Brian Carlstrom866c8622012-01-06 16:35:13 -0800692 oat_files_.push_back(&oat_file);
693}
694
Ian Rogers30fab402012-01-23 15:43:46 -0800695OatFile* ClassLinker::OpenOat(const ImageSpace* space) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700696 MutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700697 const Runtime* runtime = Runtime::Current();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700698 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800699 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
700 // check the down cast
701 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700702 std::string oat_filename;
703 oat_filename += runtime->GetHostPrefix();
704 oat_filename += oat_location->ToModifiedUtf8();
Logan Chien0c717dd2012-03-28 18:31:07 +0800705 OatFile* oat_file = OatFile::Open(oat_filename, oat_filename,
706 image_header.GetOatBegin(),
707 OatFile::kRelocNone);
Ian Rogers30fab402012-01-23 15:43:46 -0800708 VLOG(startup) << "ClassLinker::OpenOat entering oat_filename=" << oat_filename;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700709 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700710 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700711 return NULL;
712 }
713 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
714 uint32_t image_oat_checksum = image_header.GetOatChecksum();
715 if (oat_checksum != image_oat_checksum) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800716 LOG(ERROR) << "Failed to match oat file checksum " << std::hex << oat_checksum
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700717 << " to expected oat checksum " << std::hex << oat_checksum
718 << " in image";
719 return NULL;
720 }
Brian Carlstrom866c8622012-01-06 16:35:13 -0800721 RegisterOatFileLocked(*oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800722 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700723 return oat_file;
724}
725
Brian Carlstromae826982011-11-09 01:33:42 -0800726const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700727 MutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstroma004aa92012-02-08 18:05:09 -0800728 return FindOpenedOatFileFromDexLocation(dex_file.GetLocation());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800729}
730
Brian Carlstroma004aa92012-02-08 18:05:09 -0800731const OatFile* ClassLinker::FindOpenedOatFileFromDexLocation(const std::string& dex_location) {
Brian Carlstromae826982011-11-09 01:33:42 -0800732 for (size_t i = 0; i < oat_files_.size(); i++) {
733 const OatFile* oat_file = oat_files_[i];
734 DCHECK(oat_file != NULL);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800735 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, false);
Brian Carlstroma004aa92012-02-08 18:05:09 -0800736 if (oat_dex_file != NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800737 return oat_file;
738 }
739 }
740 return NULL;
741}
742
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800743static const DexFile* FindDexFileInOatLocation(const std::string& dex_location,
744 uint32_t dex_location_checksum,
745 const std::string& oat_location) {
Logan Chien0c717dd2012-03-28 18:31:07 +0800746 UniquePtr<OatFile> oat_file(
747 OatFile::Open(oat_location, oat_location, NULL, OatFile::kRelocAll));
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800748 if (oat_file.get() == NULL) {
749 return NULL;
750 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700751 Runtime* runtime = Runtime::Current();
752 const ImageHeader& image_header = runtime->GetHeap()->GetImageSpace()->GetImageHeader();
753 if (oat_file->GetOatHeader().GetImageFileLocationChecksum() != image_header.GetOatChecksum()) {
754 return NULL;
755 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800756 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
757 if (oat_dex_file == NULL) {
758 return NULL;
759 }
760 if (oat_dex_file->GetDexFileLocationChecksum() != dex_location_checksum) {
761 return NULL;
762 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700763 runtime->GetClassLinker()->RegisterOatFile(*oat_file.release());
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800764 return oat_dex_file->OpenDexFile();
765}
766
767const DexFile* ClassLinker::FindOrCreateOatFileForDexLocation(const std::string& dex_location,
768 const std::string& oat_location) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700769 MutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700770 return FindOrCreateOatFileForDexLocationLocked(dex_location, oat_location);
771}
772
773const DexFile* ClassLinker::FindOrCreateOatFileForDexLocationLocked(const std::string& dex_location,
774 const std::string& oat_location) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800775 uint32_t dex_location_checksum;
776 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) {
777 LOG(ERROR) << "Failed to compute checksum '" << dex_location << "'";
778 return NULL;
779 }
780
781 // Check if we already have an up-to-date output file
782 const DexFile* dex_file = FindDexFileInOatLocation(dex_location,
783 dex_location_checksum,
784 oat_location);
785 if (dex_file != NULL) {
786 return dex_file;
787 }
788
789 // Generate the output oat file for the dex file
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800790 UniquePtr<File> file(OS::OpenFile(oat_location.c_str(), true));
791 if (file.get() == NULL) {
792 LOG(ERROR) << "Failed to create oat file: " << oat_location;
793 return NULL;
794 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700795 if (!GenerateOatFile(dex_location, file->Fd(), oat_location)) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800796 LOG(ERROR) << "Failed to generate oat file: " << oat_location;
797 return NULL;
798 }
799 // Open the oat from file descriptor we passed to GenerateOatFile
800 if (lseek(file->Fd(), 0, SEEK_SET) != 0) {
801 LOG(ERROR) << "Failed to seek to start of generated oat file: " << oat_location;
802 return NULL;
803 }
Logan Chien0c717dd2012-03-28 18:31:07 +0800804 const OatFile* oat_file =
805 OatFile::Open(*file.get(), oat_location, NULL, OatFile::kRelocAll);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800806 if (oat_file == NULL) {
807 LOG(ERROR) << "Failed to open generated oat file: " << oat_location;
808 return NULL;
809 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700810 RegisterOatFileLocked(*oat_file);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800811 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
812 if (oat_dex_file == NULL) {
813 LOG(ERROR) << "Failed to find dex file in generated oat file: " << oat_location;
814 return NULL;
815 }
816 return oat_dex_file->OpenDexFile();
817}
818
Brian Carlstromafe25512012-06-27 17:02:58 -0700819bool ClassLinker::VerifyOatFileChecksums(const OatFile* oat_file,
820 const std::string& dex_location,
821 uint32_t dex_location_checksum) {
822 Runtime* runtime = Runtime::Current();
823 const ImageHeader& image_header = runtime->GetHeap()->GetImageSpace()->GetImageHeader();
824 uint32_t image_checksum = image_header.GetOatChecksum();
825 bool image_check = (oat_file->GetOatHeader().GetImageFileLocationChecksum() == image_checksum);
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700826
Brian Carlstromafe25512012-06-27 17:02:58 -0700827 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
828 if (oat_dex_file == NULL) {
829 LOG(ERROR) << ".oat file " << oat_file->GetLocation()
830 << " does not contain contents for " << dex_location;
831 std::vector<const OatFile::OatDexFile*> oat_dex_files = oat_file->GetOatDexFiles();
832 for (size_t i = 0; i < oat_dex_files.size(); i++) {
833 const OatFile::OatDexFile* oat_dex_file = oat_dex_files[i];
834 LOG(ERROR) << ".oat file " << oat_file->GetLocation()
835 << " contains contents for " << oat_dex_file->GetDexFileLocation();
836 }
837 return false;
838 }
839 bool dex_check = (dex_location_checksum == oat_dex_file->GetDexFileLocationChecksum());
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700840
Brian Carlstromafe25512012-06-27 17:02:58 -0700841 if (image_check && dex_check) {
842 return true;
843 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700844
Brian Carlstromafe25512012-06-27 17:02:58 -0700845 if (!image_check) {
846 std::string image_file(image_header.GetImageRoot(
847 ImageHeader::kOatLocation)->AsString()->ToModifiedUtf8());
848 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
849 << " checksum ( " << std::hex << oat_dex_file->GetDexFileLocationChecksum()
850 << ") mismatch with " << image_file
851 << " (" << std::hex << image_checksum << ")";
852 }
853 if (!dex_check) {
854 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
855 << " checksum ( " << std::hex << oat_dex_file->GetDexFileLocationChecksum()
856 << ") mismatch with " << dex_location
857 << " (" << std::hex << dex_location_checksum << ")";
858 }
859 return false;
860}
861
862const DexFile* ClassLinker::VerifyAndOpenDexFileFromOatFile(const OatFile* oat_file,
863 const std::string& dex_location,
864 uint32_t dex_location_checksum) {
865 bool verified = VerifyOatFileChecksums(oat_file, dex_location, dex_location_checksum);
866 if (!verified) {
867 return NULL;
868 }
869 RegisterOatFileLocked(*oat_file);
870 return oat_file->GetOatDexFile(dex_location)->OpenDexFile();
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700871}
872
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800873const DexFile* ClassLinker::FindDexFileInOatFileFromDexLocation(const std::string& dex_location) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700874 MutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800875
Brian Carlstroma004aa92012-02-08 18:05:09 -0800876 const OatFile* open_oat_file = FindOpenedOatFileFromDexLocation(dex_location);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800877 if (open_oat_file != NULL) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800878 return open_oat_file->GetOatDexFile(dex_location)->OpenDexFile();
Brian Carlstromae826982011-11-09 01:33:42 -0800879 }
880
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700881 // Look for an existing file next to dex. for example, for
882 // /foo/bar/baz.jar, look for /foo/bar/baz.jar.oat.
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800883 std::string oat_filename(OatFile::DexFilenameToOatFilename(dex_location));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700884 const OatFile* oat_file = FindOatFileFromOatLocationLocked(oat_filename);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800885 if (oat_file != NULL) {
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700886 uint32_t dex_location_checksum;
887 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) {
888 // If no classes.dex found in dex_location, it has been stripped, assume oat is up-to-date.
889 // This is the common case in user builds for jar's and apk's in the /system directory.
890 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location);
891 CHECK(oat_dex_file != NULL) << oat_filename << " " << dex_location;
892 RegisterOatFileLocked(*oat_file);
893 return oat_dex_file->OpenDexFile();
894 }
Brian Carlstromafe25512012-06-27 17:02:58 -0700895 const DexFile* dex_file = VerifyAndOpenDexFileFromOatFile(oat_file,
896 dex_location,
897 dex_location_checksum);
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700898 if (dex_file != NULL) {
899 return dex_file;
900 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800901 }
902 // Look for an existing file in the art-cache, validating the result if found
903 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
904 std::string cache_location(GetArtCacheFilenameOrDie(oat_filename));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700905 oat_file = FindOatFileFromOatLocationLocked(cache_location);
Brian Carlstroma004aa92012-02-08 18:05:09 -0800906 if (oat_file != NULL) {
907 uint32_t dex_location_checksum;
908 if (!DexFile::GetChecksum(dex_location, dex_location_checksum)) {
909 LOG(WARNING) << "Failed to compute checksum: " << dex_location;
910 return NULL;
911 }
Brian Carlstromafe25512012-06-27 17:02:58 -0700912 const DexFile* dex_file = VerifyAndOpenDexFileFromOatFile(oat_file,
913 dex_location,
914 dex_location_checksum);
Brian Carlstrom46b8a622012-06-19 23:13:22 -0700915 if (dex_file != NULL) {
916 return dex_file;
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700917 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800918 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
Brian Carlstrom5ef74932012-03-23 17:56:02 -0700919 PLOG(FATAL) << "Failed to remove obsolete .oat file " << oat_file->GetLocation();
Brian Carlstromd601af82012-01-06 10:15:19 -0800920 }
jeffhao262bf462011-10-20 18:36:32 -0700921 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800922 LOG(INFO) << "Failed to open oat file from " << oat_filename << " or " << cache_location << ".";
923
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800924 // Try to generate oat file if it wasn't found or was obsolete.
925 std::string oat_cache_filename(GetArtCacheFilenameOrDie(oat_filename));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700926 return FindOrCreateOatFileForDexLocationLocked(dex_location, oat_cache_filename);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700927}
928
Brian Carlstromae826982011-11-09 01:33:42 -0800929const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700930 for (size_t i = 0; i < oat_files_.size(); i++) {
931 const OatFile* oat_file = oat_files_[i];
932 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800933 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700934 return oat_file;
935 }
936 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700937 return NULL;
938}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700939
Brian Carlstromae826982011-11-09 01:33:42 -0800940const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700941 MutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700942 return FindOatFileFromOatLocationLocked(oat_location);
943}
944
945const OatFile* ClassLinker::FindOatFileFromOatLocationLocked(const std::string& oat_location) {
jeffhaof6174e82012-01-31 16:14:17 -0800946 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
947 if (oat_file != NULL) {
948 return oat_file;
949 }
950
Logan Chien0c717dd2012-03-28 18:31:07 +0800951 oat_file = OatFile::Open(oat_location, oat_location, NULL,
952 OatFile::kRelocAll);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700953 if (oat_file == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800954 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700955 }
Brian Carlstromae826982011-11-09 01:33:42 -0800956 CHECK(oat_file != NULL) << oat_location;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700957 return oat_file;
958}
959
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700960void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800961 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700962 CHECK(!init_done_);
963
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800964 Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700965 ImageSpace* space = heap->GetImageSpace();
966 OatFile* oat_file = OpenOat(space);
967 CHECK(oat_file != NULL) << "Failed to open oat file for image";
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700968 CHECK_EQ(oat_file->GetOatHeader().GetImageFileLocationChecksum(), 0U);
Elliott Hughes74847412012-06-20 18:10:21 -0700969 CHECK(oat_file->GetOatHeader().GetImageFileLocation().empty());
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700970 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
971 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700972
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700973 // Special case of setting up the String class early so that we can test arbitrary objects
974 // as being Strings or not
975 Class* java_lang_String = space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
976 ->AsObjectArray<Class>()->Get(kJavaLangString);
977 String::SetClass(java_lang_String);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800978
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700979 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
980 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers1f539342012-10-03 21:09:42 -0700981 Thread* self = Thread::Current();
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700982 for (int i = 0; i < dex_caches->GetLength(); i++) {
Ian Rogers1f539342012-10-03 21:09:42 -0700983 SirtRef<DexCache> dex_cache(self, dex_caches->Get(i));
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700984 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
985 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
986 const DexFile* dex_file = oat_dex_file->OpenDexFile();
987 if (dex_file == NULL) {
988 LOG(FATAL) << "Failed to open dex file " << dex_file_location
989 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700990 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700991
992 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
993
994 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700995 }
996
Brian Carlstroma663ea52011-08-19 23:33:41 -0700997 // reinit clases_ table
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700998 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700999 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001000 heap->FlushAllocStack();
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001001 heap->GetLiveBitmap()->Walk(InitFromImageCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001002 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001003
1004 // reinit class_roots_
Ian Rogers30fab402012-01-23 15:43:46 -08001005 Object* class_roots_object =
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001006 heap->GetImageSpace()->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
Brian Carlstrom34f426c2011-10-04 12:58:02 -07001007 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -07001008
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001009 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -07001010 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
1011 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001012 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001013 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001014 AbstractMethod::SetClasses(GetClassRoot(kJavaLangReflectConstructor),
1015 GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001016 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1017 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1018 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1019 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1020 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1021 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1022 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1023 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers5167c972012-02-03 10:41:20 -08001024 Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001025 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001026
1027 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001028
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001029 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001030}
1031
Brian Carlstrom78128a62011-09-15 17:21:19 -07001032void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001033 DCHECK(obj != NULL);
1034 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -07001035 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001036
Elliott Hughesdbb40792011-11-18 17:05:22 -08001037 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -07001038 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -07001039 return;
1040 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001041 if (obj->IsClass()) {
1042 // restore class to ClassLinker::classes_ table
1043 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001044 ClassHelper kh(klass, class_linker);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001045 Class* existing = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
1046 DCHECK(existing == NULL) << kh.GetDescriptor();
Brian Carlstroma663ea52011-08-19 23:33:41 -07001047 return;
1048 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001049}
1050
1051// Keep in sync with InitCallback. Anything we visit, we need to
1052// reinit references to when reinitializing a ClassLinker from a
1053// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -07001054void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
1055 visitor(class_roots_, arg);
Ian Rogers50b35e22012-10-04 10:09:15 -07001056 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001057 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001058 MutexLock mu(self, dex_lock_);
Elliott Hughesf8349362012-06-18 15:00:06 -07001059 for (size_t i = 0; i < dex_caches_.size(); i++) {
1060 visitor(dex_caches_[i], arg);
1061 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001062 }
1063
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001064 {
Ian Rogers50b35e22012-10-04 10:09:15 -07001065 MutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001066 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001067 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -07001068 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001069 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -07001070
1071 // We deliberately ignore the class roots in the image since we
1072 // handle image roots by using the MS/CMS rescanning of dirty cards.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001073 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001074
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001075 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001076}
1077
Elliott Hughesa2155262011-11-16 16:26:58 -08001078void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
Ian Rogers50b35e22012-10-04 10:09:15 -07001079 MutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Elliott Hughesa2155262011-11-16 16:26:58 -08001080 typedef Table::const_iterator It; // TODO: C++0x auto
1081 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
1082 if (!visitor(it->second, arg)) {
1083 return;
1084 }
1085 }
1086 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
1087 if (!visitor(it->second, arg)) {
1088 return;
1089 }
1090 }
1091}
1092
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001093static bool GetClassesVisitor(Class* c, void* arg) {
1094 std::set<Class*>* classes = reinterpret_cast<std::set<Class*>*>(arg);
1095 classes->insert(c);
1096 return true;
1097}
1098
1099void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) const {
1100 std::set<Class*> classes;
1101 VisitClasses(GetClassesVisitor, &classes);
1102 typedef std::set<Class*>::const_iterator It; // TODO: C++0x auto
1103 for (It it = classes.begin(), end = classes.end(); it != end; ++it) {
1104 if (!visitor(*it, arg)) {
1105 return;
1106 }
1107 }
1108}
1109
1110
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001111ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001112 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001113 Field::ResetClass();
Mathieu Chartier66f19252012-09-18 08:57:04 -07001114 AbstractMethod::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001115 BooleanArray::ResetArrayClass();
1116 ByteArray::ResetArrayClass();
1117 CharArray::ResetArrayClass();
1118 DoubleArray::ResetArrayClass();
1119 FloatArray::ResetArrayClass();
1120 IntArray::ResetArrayClass();
1121 LongArray::ResetArrayClass();
1122 ShortArray::ResetArrayClass();
Ian Rogers5167c972012-02-03 10:41:20 -08001123 Throwable::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001124 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001125 STLDeleteElements(&boot_class_path_);
1126 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001127}
1128
Ian Rogers50b35e22012-10-04 10:09:15 -07001129DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001130 Heap* heap = Runtime::Current()->GetHeap();
1131 Class* dex_cache_class = GetClassRoot(kJavaLangDexCache);
Ian Rogers50b35e22012-10-04 10:09:15 -07001132 SirtRef<DexCache> dex_cache(self,
1133 down_cast<DexCache*>(heap->AllocObject(self, dex_cache_class,
1134 dex_cache_class->GetObjectSize())));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001135 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001136 return NULL;
1137 }
Ian Rogers1f539342012-10-03 21:09:42 -07001138 SirtRef<String> location(self, intern_table_->InternStrong(dex_file.GetLocation().c_str()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001139 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001140 return NULL;
1141 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001142 SirtRef<ObjectArray<String> > strings(self, AllocStringArray(self, dex_file.NumStringIds()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001143 if (strings.get() == NULL) {
1144 return NULL;
1145 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001146 SirtRef<ObjectArray<Class> > types(self, AllocClassArray(self, dex_file.NumTypeIds()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001147 if (types.get() == NULL) {
1148 return NULL;
1149 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001150 SirtRef<ObjectArray<AbstractMethod> >
Ian Rogers4445a7e2012-10-05 17:19:13 -07001151 methods(self, AllocAbstractMethodArray(self, dex_file.NumMethodIds()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001152 if (methods.get() == NULL) {
1153 return NULL;
1154 }
Ian Rogers50b35e22012-10-04 10:09:15 -07001155 SirtRef<ObjectArray<Field> > fields(self, AllocFieldArray(self, dex_file.NumFieldIds()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001156 if (fields.get() == NULL) {
1157 return NULL;
1158 }
Ian Rogers1f539342012-10-03 21:09:42 -07001159 SirtRef<ObjectArray<StaticStorageBase> >
Ian Rogers50b35e22012-10-04 10:09:15 -07001160 initialized_static_storage(self,
1161 AllocObjectArray<StaticStorageBase>(self, dex_file.NumTypeIds()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001162 if (initialized_static_storage.get() == NULL) {
1163 return NULL;
1164 }
1165
Mathieu Chartier66f19252012-09-18 08:57:04 -07001166 dex_cache->Init(&dex_file,
1167 location.get(),
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001168 strings.get(),
1169 types.get(),
1170 methods.get(),
1171 fields.get(),
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001172 initialized_static_storage.get());
1173 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001174}
1175
Ian Rogers50b35e22012-10-04 10:09:15 -07001176InterfaceEntry* ClassLinker::AllocInterfaceEntry(Thread* self, Class* interface) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001177 DCHECK(interface->IsInterface());
Ian Rogers50b35e22012-10-04 10:09:15 -07001178 SirtRef<ObjectArray<Object> > array(self, AllocObjectArray<Object>(self, InterfaceEntry::LengthAsArray()));
Ian Rogers1f539342012-10-03 21:09:42 -07001179 SirtRef<InterfaceEntry> interface_entry(self, down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001180 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001181 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001182}
1183
Ian Rogers50b35e22012-10-04 10:09:15 -07001184Class* ClassLinker::AllocClass(Thread* self, Class* java_lang_Class, size_t class_size) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001185 DCHECK_GE(class_size, sizeof(Class));
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001186 Heap* heap = Runtime::Current()->GetHeap();
Ian Rogers50b35e22012-10-04 10:09:15 -07001187 SirtRef<Class> klass(self,
1188 heap->AllocObject(self, java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001189 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001190 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001191 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001192}
1193
Ian Rogers50b35e22012-10-04 10:09:15 -07001194Class* ClassLinker::AllocClass(Thread* self, size_t class_size) {
1195 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001196}
1197
Ian Rogers50b35e22012-10-04 10:09:15 -07001198Field* ClassLinker::AllocField(Thread* self) {
1199 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001200}
1201
Ian Rogers50b35e22012-10-04 10:09:15 -07001202Method* ClassLinker::AllocMethod(Thread* self) {
1203 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject(self));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001204}
1205
Ian Rogers50b35e22012-10-04 10:09:15 -07001206Constructor* ClassLinker::AllocConstructor(Thread* self) {
1207 return down_cast<Constructor*>(GetClassRoot(kJavaLangReflectConstructor)->AllocObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001208}
1209
Ian Rogers50b35e22012-10-04 10:09:15 -07001210ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(Thread* self,
1211 size_t length) {
1212 return ObjectArray<StackTraceElement>::Alloc(self,
1213 GetClassRoot(kJavaLangStackTraceElementArrayClass),
1214 length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001215}
1216
Ian Rogers50b35e22012-10-04 10:09:15 -07001217static Class* EnsureResolved(Thread* self, Class* klass)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001218 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001219 DCHECK(klass != NULL);
1220 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001221 if (!klass->IsResolved() && !klass->IsErroneous()) {
Ian Rogers1f539342012-10-03 21:09:42 -07001222 ObjectLock lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001223 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001224 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001225 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001226 PrettyDescriptor(klass).c_str());
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001227 klass->SetStatus(Class::kStatusError);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001228 return NULL;
1229 }
1230 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001231 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001232 lock.Wait();
1233 }
1234 }
1235 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001236 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001237 return NULL;
1238 }
1239 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001240 CHECK(klass->IsResolved()) << PrettyClass(klass);
1241 CHECK(!self->IsExceptionPending())
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001242 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException()) << "\n"
1243 << self->GetException()->Dump();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001244 return klass;
1245}
1246
Elliott Hughesdb7d5e92011-12-16 18:47:37 -08001247Class* ClassLinker::FindSystemClass(const char* descriptor) {
1248 return FindClass(descriptor, NULL);
1249}
1250
Ian Rogers365c1022012-06-22 15:05:28 -07001251Class* ClassLinker::FindClass(const char* descriptor, ClassLoader* class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001252 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001253 Thread* self = Thread::Current();
1254 DCHECK(self != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001255 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001256 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001257 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1258 // for primitive classes that aren't backed by dex files.
1259 return FindPrimitiveClass(descriptor[0]);
1260 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001261 // Find the class in the loaded classes table.
1262 Class* klass = LookupClass(descriptor, class_loader);
1263 if (klass != NULL) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001264 return EnsureResolved(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001265 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001266 // Class is not yet loaded.
1267 if (descriptor[0] == '[') {
1268 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001269
Jesse Wilson47daf872011-11-23 11:42:45 -05001270 } else if (class_loader == NULL) {
1271 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1272 if (pair.second != NULL) {
1273 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1274 }
1275
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001276 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Jesse Wilson47daf872011-11-23 11:42:45 -05001277 // first try the boot class path
1278 Class* system_class = FindSystemClass(descriptor);
1279 if (system_class != NULL) {
1280 return system_class;
1281 }
1282 CHECK(self->IsExceptionPending());
1283 self->ClearException();
1284
1285 // next try the compile time class path
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001286 const std::vector<const DexFile*>* class_path;
1287 {
1288 ScopedObjectAccessUnchecked soa(Thread::Current());
1289 ScopedLocalRef<jobject> jclass_loader(soa.Env(), soa.AddLocalReference<jobject>(class_loader));
1290 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
1291 }
1292
1293 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, *class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001294 if (pair.second != NULL) {
1295 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001296 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001297
1298 } else {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001299 ScopedObjectAccessUnchecked soa(self->GetJniEnv());
1300 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
1301 soa.AddLocalReference<jobject>(class_loader));
Elliott Hughes95572412011-12-13 18:14:20 -08001302 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001303 ScopedLocalRef<jobject> result(soa.Env(), NULL);
Ian Rogers365c1022012-06-22 15:05:28 -07001304 {
1305 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001306 ScopedLocalRef<jobject> class_name_object(soa.Env(),
1307 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers365c1022012-06-22 15:05:28 -07001308 if (class_name_object.get() == NULL) {
1309 return NULL;
1310 }
1311 CHECK(class_loader_object.get() != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001312 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
1313 WellKnownClasses::java_lang_ClassLoader_loadClass,
1314 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05001315 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001316 if (soa.Env()->ExceptionCheck()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001317 // If the ClassLoader threw, pass that exception up.
1318 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001319 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001320 // broken loader - throw NPE to be compatible with Dalvik
1321 ThrowNullPointerException("ClassLoader.loadClass returned null for %s",
1322 class_name_string.c_str());
1323 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001324 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08001325 // success, return Class*
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001326 return soa.Decode<Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001327 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001328 }
1329
Elliott Hughes82914b62012-04-09 15:56:29 -07001330 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001331 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001332}
1333
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001334Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Ian Rogers365c1022012-06-22 15:05:28 -07001335 ClassLoader* class_loader,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001336 const DexFile& dex_file,
1337 const DexFile::ClassDef& dex_class_def) {
Ian Rogers1f539342012-10-03 21:09:42 -07001338 Thread* self = Thread::Current();
1339 SirtRef<Class> klass(self, NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001340 // Load the class from the dex file.
1341 if (!init_done_) {
1342 // finish up init of hand crafted class_roots_
1343 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001344 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001345 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001346 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001347 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001348 klass.reset(GetClassRoot(kJavaLangString));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001349 } else if (descriptor == "Ljava/lang/DexCache;") {
1350 klass.reset(GetClassRoot(kJavaLangDexCache));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001351 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001352 klass.reset(GetClassRoot(kJavaLangReflectField));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001353 } else if (descriptor == "Ljava/lang/reflect/AbstractMethod;") {
1354 klass.reset(GetClassRoot(kJavaLangReflectAbstractMethod));
1355 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
1356 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001357 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001358 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001359 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001360 klass.reset(AllocClass(self, SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001361 }
1362 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001363 klass.reset(AllocClass(self, SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001364 }
1365 klass->SetDexCache(FindDexCache(dex_file));
1366 LoadClass(dex_file, dex_class_def, klass, class_loader);
1367 // Check for a pending exception during load
Brian Carlstromaded5f72011-10-07 17:15:04 -07001368 if (self->IsExceptionPending()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08001369 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001370 return NULL;
1371 }
Ian Rogers1f539342012-10-03 21:09:42 -07001372 ObjectLock lock(self, klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001373 klass->SetClinitThreadId(self->GetTid());
1374 // Add the newly loaded class to the loaded classes table.
Ian Rogers1f539342012-10-03 21:09:42 -07001375 SirtRef<Class> existing(self, InsertClass(descriptor, klass.get(), false));
Brian Carlstrom01e076e2012-03-30 11:54:16 -07001376 if (existing.get() != NULL) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001377 // We failed to insert because we raced with another thread.
Ian Rogers50b35e22012-10-04 10:09:15 -07001378 return EnsureResolved(self, existing.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001379 }
1380 // Finish loading (if necessary) by finding parents
1381 CHECK(!klass->IsLoaded());
1382 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1383 // Loading failed.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001384 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001385 lock.NotifyAll();
1386 return NULL;
1387 }
1388 CHECK(klass->IsLoaded());
1389 // Link the class (if necessary)
1390 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001391 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001392 // Linking failed.
Ian Rogers28ad40d2011-10-27 15:19:26 -07001393 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001394 lock.NotifyAll();
1395 return NULL;
1396 }
1397 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001398
1399 /*
1400 * We send CLASS_PREPARE events to the debugger from here. The
1401 * definition of "preparation" is creating the static fields for a
1402 * class and initializing them to the standard default values, but not
1403 * executing any code (that comes later, during "initialization").
1404 *
1405 * We did the static preparation in LinkClass.
1406 *
1407 * The class has been prepared and resolved but possibly not yet verified
1408 * at this point.
1409 */
1410 Dbg::PostClassPrepare(klass.get());
1411
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001412 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001413}
1414
Brian Carlstrom4873d462011-08-21 15:23:39 -07001415// Precomputes size that will be needed for Class, matching LinkStaticFields
1416size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1417 const DexFile::ClassDef& dex_class_def) {
1418 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001419 size_t num_ref = 0;
1420 size_t num_32 = 0;
1421 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001422 if (class_data != NULL) {
1423 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1424 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001425 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001426 char c = descriptor[0];
1427 if (c == 'L' || c == '[') {
1428 num_ref++;
1429 } else if (c == 'J' || c == 'D') {
1430 num_64++;
1431 } else {
1432 num_32++;
1433 }
1434 }
1435 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001436 // start with generic class data
1437 size_t size = sizeof(Class);
1438 // follow with reference fields which must be contiguous at start
1439 size += (num_ref * sizeof(uint32_t));
1440 // if there are 64-bit fields to add, make sure they are aligned
1441 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1442 if (num_32 != 0) {
1443 // use an available 32-bit field for padding
1444 num_32--;
1445 }
1446 size += sizeof(uint32_t); // either way, we are adding a word
1447 DCHECK_EQ(size, RoundUp(size, 8));
1448 }
1449 // tack on any 64-bit fields now that alignment is assured
1450 size += (num_64 * sizeof(uint64_t));
1451 // tack on any remaining 32-bit fields
1452 size += (num_32 * sizeof(uint32_t));
1453 return size;
1454}
1455
Ian Rogers19846512012-02-24 11:42:47 -08001456const OatFile::OatClass* ClassLinker::GetOatClass(const DexFile& dex_file, const char* descriptor) {
1457 DCHECK(descriptor != NULL);
Ian Rogers19846512012-02-24 11:42:47 -08001458 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
1459 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << descriptor;
1460 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1461 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << descriptor;
1462 uint32_t class_def_index;
1463 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1464 CHECK(found) << dex_file.GetLocation() << " " << descriptor;
1465 const OatFile::OatClass* oat_class = oat_dex_file->GetOatClass(class_def_index);
1466 CHECK(oat_class != NULL) << dex_file.GetLocation() << " " << descriptor;
1467 return oat_class;
1468}
1469
Mathieu Chartier66f19252012-09-18 08:57:04 -07001470const OatFile::OatMethod ClassLinker::GetOatMethodFor(const AbstractMethod* method) {
Ian Rogers19846512012-02-24 11:42:47 -08001471 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08001472 // method for direct methods (or virtual methods made direct).
1473 Class* declaring_class = method->GetDeclaringClass();
1474 size_t oat_method_index;
1475 if (method->IsStatic() || method->IsDirect()) {
1476 // Simple case where the oat method index was stashed at load time.
1477 oat_method_index = method->GetMethodIndex();
1478 } else {
1479 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
1480 // by search for its position in the declared virtual methods.
1481 oat_method_index = declaring_class->NumDirectMethods();
1482 size_t end = declaring_class->NumVirtualMethods();
1483 bool found = false;
1484 for (size_t i = 0; i < end; i++) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08001485 if (declaring_class->GetVirtualMethod(i) == method) {
1486 found = true;
1487 break;
1488 }
Ian Rogersf320b632012-03-13 18:47:47 -07001489 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001490 }
1491 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method);
1492 }
1493 ClassHelper kh(declaring_class);
Ian Rogers19846512012-02-24 11:42:47 -08001494 UniquePtr<const OatFile::OatClass> oat_class(GetOatClass(kh.GetDexFile(), kh.GetDescriptor()));
Brian Carlstromf5822582012-03-19 22:34:31 -07001495 CHECK(oat_class.get() != NULL);
TDYa12785321912012-04-01 15:24:56 -07001496 return oat_class->GetOatMethod(oat_method_index);
1497}
1498
1499// Special case to get oat code without overwriting a trampoline.
Mathieu Chartier66f19252012-09-18 08:57:04 -07001500const void* ClassLinker::GetOatCodeFor(const AbstractMethod* method) {
TDYa127ccffd9e2012-04-08 14:37:03 -07001501 CHECK(Runtime::Current()->IsCompiler() || method->GetDeclaringClass()->IsInitializing());
TDYa12785321912012-04-01 15:24:56 -07001502 return GetOatMethodFor(method).GetCode();
1503}
1504
Ian Rogers19846512012-02-24 11:42:47 -08001505void ClassLinker::FixupStaticTrampolines(Class* klass) {
1506 ClassHelper kh(klass);
1507 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
1508 CHECK(dex_class_def != NULL);
1509 const DexFile& dex_file = kh.GetDexFile();
1510 const byte* class_data = dex_file.GetClassData(*dex_class_def);
1511 if (class_data == NULL) {
1512 return; // no fields or methods - for example a marker interface
1513 }
Brian Carlstromf5822582012-03-19 22:34:31 -07001514 if (!Runtime::Current()->IsStarted() || Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers19846512012-02-24 11:42:47 -08001515 // OAT file unavailable
1516 return;
1517 }
Brian Carlstromf5822582012-03-19 22:34:31 -07001518 UniquePtr<const OatFile::OatClass> oat_class(GetOatClass(dex_file, kh.GetDescriptor()));
1519 CHECK(oat_class.get() != NULL);
Ian Rogers19846512012-02-24 11:42:47 -08001520 ClassDataItemIterator it(dex_file, class_data);
1521 // Skip fields
1522 while (it.HasNextStaticField()) {
1523 it.Next();
1524 }
1525 while (it.HasNextInstanceField()) {
1526 it.Next();
1527 }
1528 size_t method_index = 0;
1529 // Link the code of methods skipped by LinkCode
1530 const void* trampoline = Runtime::Current()->GetResolutionStubArray(Runtime::kStaticMethod)->GetData();
1531 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07001532 AbstractMethod* method = klass->GetDirectMethod(i);
jeffhaob5e81852012-03-12 11:15:45 -07001533 if (Runtime::Current()->IsMethodTracingActive()) {
1534 Trace* tracer = Runtime::Current()->GetTracer();
1535 if (tracer->GetSavedCodeFromMap(method) == trampoline) {
1536 const void* code = oat_class->GetOatMethod(method_index).GetCode();
1537 tracer->ResetSavedCode(method);
1538 method->SetCode(code);
1539 tracer->SaveAndUpdateCode(method);
1540 }
1541 } else if (method->GetCode() == trampoline) {
Ian Rogers19846512012-02-24 11:42:47 -08001542 const void* code = oat_class->GetOatMethod(method_index).GetCode();
Ian Rogers08f753d2012-08-24 14:35:25 -07001543 CHECK(code != NULL)
1544 << "Resolving a static trampoline but found no code for: " << PrettyMethod(method);
Ian Rogers19846512012-02-24 11:42:47 -08001545 method->SetCode(code);
1546 }
1547 method_index++;
1548 }
1549}
1550
Mathieu Chartier66f19252012-09-18 08:57:04 -07001551static void LinkCode(SirtRef<AbstractMethod>& method, const OatFile::OatClass* oat_class,
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001552 uint32_t method_index)
Ian Rogersb726dcb2012-09-05 08:57:23 -07001553 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001554 // Every kind of method should at least get an invoke stub from the oat_method.
1555 // non-abstract methods also get their code pointers.
1556 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001557 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001558
Ian Rogers19846512012-02-24 11:42:47 -08001559 Runtime* runtime = Runtime::Current();
Brian Carlstrom92827a52011-10-10 15:50:01 -07001560 if (method->IsAbstract()) {
Ian Rogers19846512012-02-24 11:42:47 -08001561 method->SetCode(runtime->GetAbstractMethodErrorStubArray()->GetData());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001562 return;
1563 }
Ian Rogers19846512012-02-24 11:42:47 -08001564
1565 if (method->IsStatic() && !method->IsConstructor()) {
1566 // For static methods excluding the class initializer, install the trampoline
1567 method->SetCode(runtime->GetResolutionStubArray(Runtime::kStaticMethod)->GetData());
Ian Rogers0d6de042012-02-29 08:50:26 -08001568 }
1569 if (method->IsNative()) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001570 // unregistering restores the dlsym lookup stub
Ian Rogers19846512012-02-24 11:42:47 -08001571 method->UnregisterNative(Thread::Current());
jeffhao26c0a1a2012-01-17 16:28:33 -08001572 }
1573
1574 if (Runtime::Current()->IsMethodTracingActive()) {
jeffhao26c0a1a2012-01-17 16:28:33 -08001575 Trace* tracer = Runtime::Current()->GetTracer();
jeffhaob5e81852012-03-12 11:15:45 -07001576 tracer->SaveAndUpdateCode(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001577 }
1578}
1579
Brian Carlstromf615a612011-07-23 12:50:34 -07001580void ClassLinker::LoadClass(const DexFile& dex_file,
1581 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001582 SirtRef<Class>& klass,
Ian Rogers365c1022012-06-22 15:05:28 -07001583 ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001584 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001585 CHECK(klass->GetDexCache() != NULL);
1586 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001587 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001588 CHECK(descriptor != NULL);
1589
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001590 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001591 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001592 // Make sure that none of our runtime-only flags are set.
1593 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001594 klass->SetAccessFlags(access_flags);
1595 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001596 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001597 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001598
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001599 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001600
Ian Rogers0571d352011-11-03 19:51:38 -07001601 // Load fields fields.
1602 const byte* class_data = dex_file.GetClassData(dex_class_def);
1603 if (class_data == NULL) {
1604 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001605 }
Ian Rogers0571d352011-11-03 19:51:38 -07001606 ClassDataItemIterator it(dex_file, class_data);
Ian Rogers50b35e22012-10-04 10:09:15 -07001607 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07001608 if (it.NumStaticFields() != 0) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07001609 klass->SetSFields(AllocFieldArray(self, it.NumStaticFields()));
Ian Rogers0571d352011-11-03 19:51:38 -07001610 }
1611 if (it.NumInstanceFields() != 0) {
Ian Rogers4445a7e2012-10-05 17:19:13 -07001612 klass->SetIFields(AllocFieldArray(self, it.NumInstanceFields()));
Ian Rogers0571d352011-11-03 19:51:38 -07001613 }
1614 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001615 SirtRef<Field> sfield(self, AllocField(self));
Ian Rogers0571d352011-11-03 19:51:38 -07001616 klass->SetStaticField(i, sfield.get());
1617 LoadField(dex_file, it, klass, sfield);
1618 }
1619 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001620 SirtRef<Field> ifield(self, AllocField(self));
Ian Rogers0571d352011-11-03 19:51:38 -07001621 klass->SetInstanceField(i, ifield.get());
1622 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001623 }
1624
Brian Carlstromf5822582012-03-19 22:34:31 -07001625 UniquePtr<const OatFile::OatClass> oat_class;
1626 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
1627 oat_class.reset(GetOatClass(dex_file, descriptor));
1628 }
Ian Rogers19846512012-02-24 11:42:47 -08001629
Ian Rogers0571d352011-11-03 19:51:38 -07001630 // Load methods.
1631 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001632 // TODO: append direct methods to class object
Ian Rogers4445a7e2012-10-05 17:19:13 -07001633 klass->SetDirectMethods(AllocAbstractMethodArray(self, it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001634 }
Ian Rogers0571d352011-11-03 19:51:38 -07001635 if (it.NumVirtualMethods() != 0) {
1636 // TODO: append direct methods to class object
Ian Rogers4445a7e2012-10-05 17:19:13 -07001637 klass->SetVirtualMethods(AllocMethodArray(self, it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001638 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08001639 size_t class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001640 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001641 SirtRef<AbstractMethod> method(self, LoadMethod(self, dex_file, it, klass));
Ian Rogers0571d352011-11-03 19:51:38 -07001642 klass->SetDirectMethod(i, method.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001643 if (oat_class.get() != NULL) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08001644 LinkCode(method, oat_class.get(), class_def_method_index);
Ian Rogers0571d352011-11-03 19:51:38 -07001645 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08001646 method->SetMethodIndex(class_def_method_index);
1647 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001648 }
1649 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001650 SirtRef<AbstractMethod> method(self, LoadMethod(self, dex_file, it, klass));
Ian Rogers0571d352011-11-03 19:51:38 -07001651 klass->SetVirtualMethod(i, method.get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08001652 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers0571d352011-11-03 19:51:38 -07001653 if (oat_class.get() != NULL) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08001654 LinkCode(method, oat_class.get(), class_def_method_index);
Ian Rogers0571d352011-11-03 19:51:38 -07001655 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08001656 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001657 }
1658 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001659}
1660
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001661void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Ian Rogers0571d352011-11-03 19:51:38 -07001662 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001663 uint32_t field_idx = it.GetMemberIndex();
1664 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001665 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001666 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001667}
1668
Ian Rogers50b35e22012-10-04 10:09:15 -07001669AbstractMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
1670 const ClassDataItemIterator& it,
1671 SirtRef<Class>& klass) {
Ian Rogers19846512012-02-24 11:42:47 -08001672 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08001673 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001674 StringPiece method_name(dex_file.GetMethodName(method_id));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001675
1676 AbstractMethod* dst = NULL;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001677 if (method_name == "<init>") {
Ian Rogers50b35e22012-10-04 10:09:15 -07001678 dst = AllocConstructor(self);
Mathieu Chartier66f19252012-09-18 08:57:04 -07001679 } else {
Ian Rogers50b35e22012-10-04 10:09:15 -07001680 dst = AllocMethod(self);
Elliott Hughes80609252011-09-23 17:24:51 -07001681 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07001682 DCHECK(dst->IsMethod()) << PrettyDescriptor(dst->GetClass());
1683
Ian Rogers50b35e22012-10-04 10:09:15 -07001684 const char* old_cause = self->StartAssertNoThreadSuspension("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07001685 dst->SetDexMethodIndex(dex_method_idx);
1686 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001687
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001688 if (method_name == "finalize") {
1689 // Create the prototype for a signature of "()V"
1690 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1691 if (void_string_id != NULL) {
1692 const DexFile::TypeId* void_type_id =
1693 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1694 if (void_type_id != NULL) {
1695 std::vector<uint16_t> no_args;
1696 const DexFile::ProtoId* finalizer_proto =
1697 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1698 if (finalizer_proto != NULL) {
1699 // We have the prototype in the dex file
1700 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1701 klass->SetFinalizable();
1702 } else {
1703 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1704 // The Enum class declares a "final" finalize() method to prevent subclasses from
1705 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1706 // subclasses, so we exclude it here.
1707 // We also want to avoid setting the flag on Object, where we know that finalize() is
1708 // empty.
1709 if (klass_descriptor != "Ljava/lang/Object;" &&
1710 klass_descriptor != "Ljava/lang/Enum;") {
1711 klass->SetFinalizable();
1712 }
1713 }
1714 }
1715 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001716 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001717 }
Ian Rogers0571d352011-11-03 19:51:38 -07001718 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001719 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001720
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001721 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
Ian Rogers19846512012-02-24 11:42:47 -08001722 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001723 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001724 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Mathieu Chartier66f19252012-09-18 08:57:04 -07001725
1726 CHECK(dst->IsMethod());
1727
Ian Rogers50b35e22012-10-04 10:09:15 -07001728 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartier66f19252012-09-18 08:57:04 -07001729 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07001730}
1731
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001732void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001733 Thread* self = Thread::Current();
1734 SirtRef<DexCache> dex_cache(self, AllocDexCache(self, dex_file));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001735 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001736}
1737
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001738void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1739 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001740 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001741 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001742}
1743
Brian Carlstromaded5f72011-10-07 17:15:04 -07001744bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Ian Rogers50b35e22012-10-04 10:09:15 -07001745 dex_lock_.AssertHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07001746 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1747 if (dex_caches_[i]->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08001748 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001749 }
1750 }
1751 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001752}
1753
Brian Carlstromaded5f72011-10-07 17:15:04 -07001754bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Ian Rogers50b35e22012-10-04 10:09:15 -07001755 MutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001756 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001757}
1758
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001759void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001760 dex_lock_.AssertHeld(Thread::Current());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001761 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001762 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001763 dex_caches_.push_back(dex_cache.get());
Mathieu Chartier66f19252012-09-18 08:57:04 -07001764 dex_cache->SetDexFile(&dex_file);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001765}
1766
Brian Carlstromaded5f72011-10-07 17:15:04 -07001767void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07001768 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001769 {
Ian Rogers1f539342012-10-03 21:09:42 -07001770 MutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001771 if (IsDexFileRegisteredLocked(dex_file)) {
1772 return;
1773 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001774 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001775 // Don't alloc while holding the lock, since allocation may need to
1776 // suspend all threads and another thread may need the dex_lock_ to
1777 // get to a suspend point.
Ian Rogers50b35e22012-10-04 10:09:15 -07001778 SirtRef<DexCache> dex_cache(self, AllocDexCache(self, dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001779 {
Ian Rogers1f539342012-10-03 21:09:42 -07001780 MutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001781 if (IsDexFileRegisteredLocked(dex_file)) {
1782 return;
1783 }
1784 RegisterDexFileLocked(dex_file, dex_cache);
1785 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001786}
1787
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001788void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001789 MutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001790 RegisterDexFileLocked(dex_file, dex_cache);
1791}
1792
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001793DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Ian Rogers50b35e22012-10-04 10:09:15 -07001794 MutexLock mu(Thread::Current(), dex_lock_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07001795 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1796 DexCache* dex_cache = dex_caches_[i];
1797 if (dex_cache->GetDexFile() == &dex_file) {
1798 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001799 }
1800 }
Elliott Hughes7b9d9962012-04-20 18:48:18 -07001801 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001802 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001803}
1804
Mathieu Chartier66f19252012-09-18 08:57:04 -07001805void ClassLinker::FixupDexCaches(AbstractMethod* resolution_method) const {
Ian Rogers50b35e22012-10-04 10:09:15 -07001806 MutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08001807 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1808 dex_caches_[i]->Fixup(resolution_method);
1809 }
1810}
1811
Ian Rogersc8982582012-09-07 16:53:25 -07001812Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class, Primitive::Type type) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001813 CHECK(primitive_class != NULL);
Ian Rogers1f539342012-10-03 21:09:42 -07001814 // Must hold lock on object when initializing.
1815 ObjectLock lock(Thread::Current(), primitive_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001816 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001817 primitive_class->SetPrimitiveType(type);
1818 primitive_class->SetStatus(Class::kStatusInitialized);
Ian Rogersc8982582012-09-07 16:53:25 -07001819 Class* existing = InsertClass(Primitive::Descriptor(type), primitive_class, false);
1820 CHECK(existing == NULL) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001821 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001822}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001823
Brian Carlstrombe977852011-07-19 14:54:54 -07001824// Create an array class (i.e. the class object for the array, not the
1825// array itself). "descriptor" looks like "[C" or "[[[[B" or
1826// "[Ljava/lang/String;".
1827//
1828// If "descriptor" refers to an array of primitives, look up the
1829// primitive type's internally-generated class object.
1830//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001831// "class_loader" is the class loader of the class that's referring to
1832// us. It's used to ensure that we're looking for the element type in
1833// the right context. It does NOT become the class loader for the
1834// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001835//
1836// Returns NULL with an exception raised on failure.
Ian Rogers365c1022012-06-22 15:05:28 -07001837Class* ClassLinker::CreateArrayClass(const std::string& descriptor, ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001838 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001839
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001840 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001841 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001842 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001843 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001844 return NULL;
1845 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001846
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001847 // See if the component type is already loaded. Array classes are
1848 // always associated with the class loader of their underlying
1849 // element type -- an array of Strings goes with the loader for
1850 // java/lang/String -- so we need to look for it there. (The
1851 // caller should have checked for the existence of the class
1852 // before calling here, but they did so with *their* class loader,
1853 // not the component type's loader.)
1854 //
1855 // If we find it, the caller adds "loader" to the class' initiating
1856 // loader list, which should prevent us from going through this again.
1857 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001858 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001859 // are the same, because our caller (FindClass) just did the
1860 // lookup. (Even if we get this wrong we still have correct behavior,
1861 // because we effectively do this lookup again when we add the new
1862 // class to the hash table --- necessary because of possible races with
1863 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001864 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001865 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001866 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001867 return new_class;
1868 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001869 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001870
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001871 // Fill out the fields in the Class.
1872 //
1873 // It is possible to execute some methods against arrays, because
1874 // all arrays are subclasses of java_lang_Object_, so we need to set
1875 // up a vtable. We can just point at the one in java_lang_Object_.
1876 //
1877 // Array classes are simple enough that we don't need to do a full
1878 // link step.
Ian Rogers1f539342012-10-03 21:09:42 -07001879 Thread* self = Thread::Current();
1880 SirtRef<Class> new_class(self, NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001881 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001882 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001883 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001884 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001885 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001886 new_class.reset(GetClassRoot(kObjectArrayClass));
Ian Rogers23435d02012-09-24 11:23:12 -07001887 } else if (descriptor == "[[Ljava/lang/Object;") {
1888 new_class.reset(GetClassRoot(kObjectArrayArrayClass));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001889 } else if (descriptor == class_roots_descriptors_[kJavaLangStringArrayClass]) {
1890 new_class.reset(GetClassRoot(kJavaLangStringArrayClass));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001891 } else if (descriptor == class_roots_descriptors_[kJavaLangReflectAbstractMethodArrayClass]) {
1892 new_class.reset(GetClassRoot(kJavaLangReflectAbstractMethodArrayClass));
Ian Rogers4445a7e2012-10-05 17:19:13 -07001893 } else if (descriptor == class_roots_descriptors_[kJavaLangReflectFieldArrayClass]) {
1894 new_class.reset(GetClassRoot(kJavaLangReflectFieldArrayClass));
1895 } else if (descriptor == class_roots_descriptors_[kJavaLangReflectMethodArrayClass]) {
1896 new_class.reset(GetClassRoot(kJavaLangReflectMethodArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001897 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001898 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001899 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001900 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001901 }
1902 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001903 if (new_class.get() == NULL) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001904 new_class.reset(AllocClass(self, sizeof(Class)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001905 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001906 return NULL;
1907 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001908 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001909 }
Ian Rogers1f539342012-10-03 21:09:42 -07001910 ObjectLock lock(self, new_class.get()); // Must hold lock on object when initializing.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001911 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001912 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001913 new_class->SetSuperClass(java_lang_Object);
1914 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001915 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001916 new_class->SetClassLoader(component_type->GetClassLoader());
1917 new_class->SetStatus(Class::kStatusInitialized);
1918 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001919 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001920
1921
1922 // All arrays have java/lang/Cloneable and java/io/Serializable as
1923 // interfaces. We need to set that up here, so that stuff like
1924 // "instanceof" works right.
1925 //
1926 // Note: The GC could run during the call to FindSystemClass,
1927 // so we need to make sure the class object is GC-valid while we're in
1928 // there. Do this by clearing the interface list so the GC will just
1929 // think that the entries are null.
1930
1931
1932 // Use the single, global copies of "interfaces" and "iftable"
1933 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001934 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001935 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001936
1937 // Inherit access flags from the component type. Arrays can't be
1938 // used as a superclass or interface, so we want to add "final"
1939 // and remove "interface".
1940 //
1941 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001942 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001943 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001944 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1945 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001946
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001947 Class* existing = InsertClass(descriptor, new_class.get(), false);
1948 if (existing == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001949 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001950 }
1951 // Another thread must have loaded the class after we
1952 // started but before we finished. Abandon what we've
1953 // done.
1954 //
1955 // (Yes, this happens.)
1956
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001957 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001958}
1959
1960Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001961 switch (Primitive::GetType(type)) {
1962 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001963 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001964 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001965 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001966 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001967 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001968 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001969 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001970 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001971 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001972 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001973 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001974 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001975 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001976 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001977 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001978 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001979 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001980 case Primitive::kPrimNot:
1981 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001982 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001983 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001984 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001985 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001986}
1987
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001988Class* ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001989 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001990 DexCache* dex_cache = klass->GetDexCache();
1991 std::string source;
1992 if (dex_cache != NULL) {
1993 source += " from ";
1994 source += dex_cache->GetLocation()->ToModifiedUtf8();
1995 }
1996 LOG(INFO) << "Loaded class " << descriptor << source;
1997 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001998 size_t hash = StringPieceHash()(descriptor);
Ian Rogers50b35e22012-10-04 10:09:15 -07001999 MutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002000 Table& classes = image_class ? image_classes_ : classes_;
Elliott Hughesf8349362012-06-18 15:00:06 -07002001 Class* existing = LookupClassLocked(descriptor.data(), klass->GetClassLoader(), hash, classes);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002002#ifndef NDEBUG
2003 // Check we don't have the class in the other table in error
2004 Table& other_classes = image_class ? classes_ : image_classes_;
Elliott Hughesf8349362012-06-18 15:00:06 -07002005 CHECK(LookupClassLocked(descriptor.data(), klass->GetClassLoader(), hash, other_classes) == NULL);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002006#endif
2007 if (existing != NULL) {
2008 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07002009 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002010 classes.insert(std::make_pair(hash, klass));
2011 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002012}
2013
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002014bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
2015 size_t hash = Hash(descriptor);
Ian Rogers50b35e22012-10-04 10:09:15 -07002016 MutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Elliott Hughese5448b52012-01-18 16:44:06 -08002017 typedef Table::iterator It; // TODO: C++0x auto
Brian Carlstromae826982011-11-09 01:33:42 -08002018 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002019 ClassHelper kh;
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002020 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08002021 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002022 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002023 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08002024 classes_.erase(it);
2025 return true;
2026 }
2027 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002028 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08002029 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002030 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002031 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08002032 image_classes_.erase(it);
2033 return true;
2034 }
2035 }
2036 return false;
2037}
2038
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002039Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
2040 size_t hash = Hash(descriptor);
Ian Rogers50b35e22012-10-04 10:09:15 -07002041 MutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07002042 // TODO: determine if its better to search classes_ or image_classes_ first
Elliott Hughesf8349362012-06-18 15:00:06 -07002043 Class* klass = LookupClassLocked(descriptor, class_loader, hash, classes_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002044 if (klass != NULL) {
2045 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002046 }
Elliott Hughesf8349362012-06-18 15:00:06 -07002047 return LookupClassLocked(descriptor, class_loader, hash, image_classes_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002048}
2049
Elliott Hughesf8349362012-06-18 15:00:06 -07002050Class* ClassLinker::LookupClassLocked(const char* descriptor, const ClassLoader* class_loader,
2051 size_t hash, const Table& classes) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002052 ClassHelper kh(NULL, this);
2053 typedef Table::const_iterator It; // TODO: C++0x auto
2054 for (It it = classes.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers5d76c432011-10-31 21:42:49 -07002055 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002056 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002057 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002058#ifndef NDEBUG
2059 for (++it; it != end && it->first == hash; ++it) {
Ian Rogersd85016c2012-02-03 18:27:34 -08002060 Class* klass2 = it->second;
2061 kh.ChangeClass(klass2);
2062 CHECK(!(strcmp(descriptor, kh.GetDescriptor()) == 0 && klass2->GetClassLoader() == class_loader))
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002063 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
Ian Rogersd85016c2012-02-03 18:27:34 -08002064 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002065 }
2066#endif
Ian Rogers5d76c432011-10-31 21:42:49 -07002067 return klass;
2068 }
2069 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002070 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002071}
2072
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002073void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002074 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002075 size_t hash = Hash(descriptor);
Ian Rogers50b35e22012-10-04 10:09:15 -07002076 MutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002077 typedef Table::const_iterator It; // TODO: C++0x auto
2078 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002079 ClassHelper kh(NULL, this);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002080 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002081 Class* klass = it->second;
2082 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002083 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002084 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002085 }
2086 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002087 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002088 Class* klass = it->second;
2089 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002090 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002091 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002092 }
2093 }
2094}
2095
jeffhao98eacac2011-09-14 16:11:53 -07002096void ClassLinker::VerifyClass(Class* klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002097 // TODO: assert that the monitor on the Class is held
Ian Rogers1f539342012-10-03 21:09:42 -07002098 Thread* self = Thread::Current();
2099 ObjectLock lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08002100
Ian Rogers9ffb0392012-09-10 11:56:50 -07002101 // Don't attempt to re-verify if already sufficiently verified.
2102 if (klass->IsVerified() ||
2103 (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler())) {
jeffhao98eacac2011-09-14 16:11:53 -07002104 return;
2105 }
2106
Ian Rogers9ffb0392012-09-10 11:56:50 -07002107 // The class might already be erroneous, for example at compile time if we attempted to verify
2108 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002109 if (klass->IsErroneous()) {
2110 ThrowEarlierClassFailure(klass);
2111 return;
2112 }
2113
Ian Rogers9ffb0392012-09-10 11:56:50 -07002114 if (klass->GetStatus() == Class::kStatusResolved) {
2115 klass->SetStatus(Class::kStatusVerifying);
2116 } else {
2117 CHECK_EQ(klass->GetStatus(), Class::kStatusRetryVerificationAtRuntime) << PrettyClass(klass);
2118 CHECK(!Runtime::Current()->IsCompiler());
2119 klass->SetStatus(Class::kStatusVerifyingAtRuntime);
2120 }
jeffhao98eacac2011-09-14 16:11:53 -07002121
Ian Rogers9ffb0392012-09-10 11:56:50 -07002122 // Verify super class.
Ian Rogers1c5eb702012-02-01 09:18:34 -08002123 Class* super = klass->GetSuperClass();
2124 std::string error_msg;
2125 if (super != NULL) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07002126 // Acquire lock to prevent races on verifying the super class.
Ian Rogers1f539342012-10-03 21:09:42 -07002127 ObjectLock lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002128
2129 if (!super->IsVerified() && !super->IsErroneous()) {
2130 Runtime::Current()->GetClassLinker()->VerifyClass(super);
2131 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002132 if (!super->IsCompileTimeVerified()) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08002133 error_msg = "Rejecting class ";
2134 error_msg += PrettyDescriptor(klass);
2135 error_msg += " that attempts to sub-class erroneous class ";
2136 error_msg += PrettyDescriptor(super);
2137 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Ian Rogers1f539342012-10-03 21:09:42 -07002138 SirtRef<Throwable> cause(self, self->GetException());
Ian Rogers1c5eb702012-02-01 09:18:34 -08002139 if (cause.get() != NULL) {
2140 self->ClearException();
2141 }
2142 self->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
2143 if (cause.get() != NULL) {
2144 self->GetException()->SetCause(cause.get());
2145 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08002146 klass->SetStatus(Class::kStatusError);
2147 return;
2148 }
2149 }
2150
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002151 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07002152 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002153 Class::Status oat_file_class_status(Class::kStatusNotReady);
2154 bool preverified = VerifyClassUsingOatFile(dex_file, klass, oat_file_class_status);
jeffhaof1e6b7c2012-06-05 18:33:30 -07002155 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
jeffhaoec014232012-09-05 10:42:25 -07002156 if (oat_file_class_status == Class::kStatusError) {
2157 LOG(WARNING) << "Skipping runtime verification of erroneous class " << PrettyDescriptor(klass)
2158 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
2159 error_msg = "Rejecting class ";
2160 error_msg += PrettyDescriptor(klass);
2161 error_msg += " because it failed compile-time verification";
2162 Thread::Current()->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
2163 klass->SetStatus(Class::kStatusError);
2164 return;
2165 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002166 if (!preverified) {
2167 verifier_failure = verifier::MethodVerifier::VerifyClass(klass, error_msg);
2168 }
2169 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07002170 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
2171 LOG(WARNING) << "Soft verification failure in class " << PrettyDescriptor(klass)
2172 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2173 << " because: " << error_msg;
2174 }
Ian Rogers1f539342012-10-03 21:09:42 -07002175 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002176 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002177 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002178 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
2179 klass->SetStatus(Class::kStatusVerified);
2180 } else {
2181 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
2182 // Soft failures at compile time should be retried at runtime. Soft
2183 // failures at runtime will be handled by slow paths in the generated
2184 // code. Set status accordingly.
2185 if (Runtime::Current()->IsCompiler()) {
2186 klass->SetStatus(Class::kStatusRetryVerificationAtRuntime);
2187 } else {
2188 klass->SetStatus(Class::kStatusVerified);
2189 }
2190 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07002191 } else {
Ian Rogers09f6b562012-01-31 21:58:52 -08002192 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass)
Ian Rogers1c5eb702012-02-01 09:18:34 -08002193 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2194 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002195 self->AssertNoPendingException();
Ian Rogers1c5eb702012-02-01 09:18:34 -08002196 self->ThrowNewException("Ljava/lang/VerifyError;", error_msg.c_str());
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002197 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07002198 }
jeffhao98eacac2011-09-14 16:11:53 -07002199}
2200
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002201bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, Class* klass,
2202 Class::Status& oat_file_class_status) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002203 if (!Runtime::Current()->IsStarted()) {
2204 return false;
2205 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002206 if (Runtime::Current()->UseCompileTimeClassPath()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002207 return false;
2208 }
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002209 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
2210 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002211 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002212 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002213 const char* descriptor = ClassHelper(klass).GetDescriptor();
2214 uint32_t class_def_index;
2215 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002216 CHECK(found) << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002217 UniquePtr<const OatFile::OatClass> oat_class(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002218 CHECK(oat_class.get() != NULL)
2219 << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002220 oat_file_class_status = oat_class->GetStatus();
Ian Rogers9ffb0392012-09-10 11:56:50 -07002221 if (oat_file_class_status == Class::kStatusVerified ||
2222 oat_file_class_status == Class::kStatusInitialized) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002223 return true;
2224 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002225 if (oat_file_class_status == Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07002226 // Compile time verification failed with a soft error. Compile time verification can fail
2227 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08002228 // class ... {
2229 // Foo x;
2230 // .... () {
2231 // if (...) {
2232 // v1 gets assigned a type of resolved class Foo
2233 // } else {
2234 // v1 gets assigned a type of unresolved class Bar
2235 // }
2236 // iput x = v1
2237 // } }
2238 // when we merge v1 following the if-the-else it results in Conflict
2239 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
2240 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
2241 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
2242 // at compile time).
2243 return false;
2244 }
jeffhao1ac29442012-03-26 11:37:32 -07002245 if (oat_file_class_status == Class::kStatusError) {
2246 // Compile time verification failed with a hard error. This is caused by invalid instructions
2247 // in the class. These errors are unrecoverable.
2248 return false;
2249 }
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002250 if (oat_file_class_status == Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08002251 // Status is uninitialized if we couldn't determine the status at compile time, for example,
2252 // not loading the class.
2253 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
2254 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002255 return false;
2256 }
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002257 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Brian Carlstrom5b332c82012-02-01 15:02:31 -08002258 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " " << descriptor;
2259
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002260 return false;
2261}
2262
2263void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, Class* klass) {
2264 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
2265 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
2266 }
2267 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
2268 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
2269 }
2270}
2271
Mathieu Chartier66f19252012-09-18 08:57:04 -07002272void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, AbstractMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002273 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
2274 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
2275 if (code_item == NULL) {
2276 return; // native or abstract method
2277 }
2278 if (code_item->tries_size_ == 0) {
2279 return; // nothing to process
2280 }
2281 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
2282 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2283 ClassLinker* linker = Runtime::Current()->GetClassLinker();
2284 for (uint32_t idx = 0; idx < handlers_size; idx++) {
2285 CatchHandlerIterator iterator(handlers_ptr);
2286 for (; iterator.HasNext(); iterator.Next()) {
2287 // Ensure exception types are resolved so that they don't need resolution to be delivered,
2288 // unresolved exception types will be ignored by exception delivery
2289 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
2290 Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
2291 if (exception_type == NULL) {
2292 DCHECK(Thread::Current()->IsExceptionPending());
2293 Thread::Current()->ClearException();
2294 }
2295 }
2296 }
2297 handlers_ptr = iterator.EndDataPointer();
2298 }
2299}
2300
Mathieu Chartier66f19252012-09-18 08:57:04 -07002301static void CheckProxyConstructor(AbstractMethod* constructor);
2302static void CheckProxyMethod(AbstractMethod* method, SirtRef<AbstractMethod>& prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08002303
Jesse Wilson95caa792011-10-12 18:14:17 -04002304Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Mathieu Chartier66f19252012-09-18 08:57:04 -07002305 ClassLoader* loader, ObjectArray<AbstractMethod>* methods,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002306 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogers1f539342012-10-03 21:09:42 -07002307 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07002308 SirtRef<Class> klass(self, AllocClass(self, GetClassRoot(kJavaLangClass),
2309 sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002310 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08002311 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04002312 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002313 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002314 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002315 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002316 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07002317 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002318 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08002319
2320 klass->SetStatus(Class::kStatusIdx);
2321
2322 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
2323
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002324 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogers4445a7e2012-10-05 17:19:13 -07002325 klass->SetSFields(AllocFieldArray(self, 2));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002326 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
2327 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Ian Rogers50b35e22012-10-04 10:09:15 -07002328 SirtRef<Field> interfaces_sfield(self, AllocField(self));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002329 klass->SetStaticField(0, interfaces_sfield.get());
2330 interfaces_sfield->SetDexFieldIndex(0);
2331 interfaces_sfield->SetDeclaringClass(klass.get());
2332 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
2333 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Ian Rogers50b35e22012-10-04 10:09:15 -07002334 SirtRef<Field> throws_sfield(self, AllocField(self));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002335 klass->SetStaticField(1, throws_sfield.get());
2336 throws_sfield->SetDexFieldIndex(1);
2337 throws_sfield->SetDeclaringClass(klass.get());
2338 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002339
Ian Rogers466bb252011-10-14 03:29:56 -07002340 // Proxies have 1 direct method, the constructor
Ian Rogers4445a7e2012-10-05 17:19:13 -07002341 klass->SetDirectMethods(AllocAbstractMethodArray(self, 1));
Ian Rogers50b35e22012-10-04 10:09:15 -07002342 klass->SetDirectMethod(0, CreateProxyConstructor(self, klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04002343
Ian Rogers466bb252011-10-14 03:29:56 -07002344 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04002345 size_t num_virtual_methods = methods->GetLength();
Ian Rogers4445a7e2012-10-05 17:19:13 -07002346 klass->SetVirtualMethods(AllocMethodArray(self, num_virtual_methods));
Jesse Wilson95caa792011-10-12 18:14:17 -04002347 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers1f539342012-10-03 21:09:42 -07002348 SirtRef<AbstractMethod> prototype(self, methods->Get(i));
Ian Rogers50b35e22012-10-04 10:09:15 -07002349 klass->SetVirtualMethod(i, CreateProxyMethod(self, klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04002350 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002351
2352 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
2353 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
2354 DCHECK(!Thread::Current()->IsExceptionPending());
2355
2356 // Link the fields and virtual methods, creating vtable and iftables
2357 if (!LinkClass(klass, interfaces)) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002358 klass->SetStatus(Class::kStatusError);
Jesse Wilson95caa792011-10-12 18:14:17 -04002359 return NULL;
2360 }
Ian Rogersc8982582012-09-07 16:53:25 -07002361 {
Ian Rogers1f539342012-10-03 21:09:42 -07002362 ObjectLock lock(self, klass.get()); // Must hold lock on object when initializing.
Ian Rogersc8982582012-09-07 16:53:25 -07002363 interfaces_sfield->SetObject(NULL, interfaces);
2364 throws_sfield->SetObject(NULL, throws);
2365 klass->SetStatus(Class::kStatusInitialized);
2366 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002367
2368 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07002369 if (kIsDebugBuild) {
Ian Rogersc2b44472011-12-14 21:17:17 -08002370 CHECK(klass->GetIFields() == NULL);
2371 CheckProxyConstructor(klass->GetDirectMethod(0));
2372 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers1f539342012-10-03 21:09:42 -07002373 SirtRef<AbstractMethod> prototype(self, methods->Get(i));
Ian Rogersc2b44472011-12-14 21:17:17 -08002374 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
2375 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002376
2377 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
2378 name->ToModifiedUtf8().c_str()));
2379 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
2380
2381 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
2382 name->ToModifiedUtf8().c_str()));
2383 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08002384
2385 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002386 CHECK_EQ(synth_proxy_class->GetInterfaces(), interfaces);
Ian Rogersc2b44472011-12-14 21:17:17 -08002387 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
2388 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002389 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04002390}
2391
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002392std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
2393 DCHECK(proxy_class->IsProxyClass());
2394 String* name = proxy_class->GetName();
2395 DCHECK(name != NULL);
2396 return DotToDescriptor(name->ToModifiedUtf8().c_str());
2397}
2398
Mathieu Chartier66f19252012-09-18 08:57:04 -07002399AbstractMethod* ClassLinker::FindMethodForProxy(const Class* proxy_class, const AbstractMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08002400 DCHECK(proxy_class->IsProxyClass());
2401 DCHECK(proxy_method->IsProxyMethod());
2402 // Locate the dex cache of the original interface/Object
2403 DexCache* dex_cache = NULL;
2404 {
2405 ObjectArray<Class>* resolved_types = proxy_method->GetDexCacheResolvedTypes();
Ian Rogers50b35e22012-10-04 10:09:15 -07002406 MutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08002407 for (size_t i = 0; i != dex_caches_.size(); ++i) {
2408 if (dex_caches_[i]->GetResolvedTypes() == resolved_types) {
2409 dex_cache = dex_caches_[i];
2410 break;
2411 }
2412 }
2413 }
2414 CHECK(dex_cache != NULL);
2415 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Mathieu Chartier66f19252012-09-18 08:57:04 -07002416 AbstractMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Ian Rogers16f93672012-02-14 12:29:06 -08002417 CHECK(resolved_method != NULL);
2418 return resolved_method;
2419}
2420
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002421
Ian Rogers50b35e22012-10-04 10:09:15 -07002422AbstractMethod* ClassLinker::CreateProxyConstructor(Thread* self, SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07002423 // Create constructor for Proxy that must initialize h
Mathieu Chartier66f19252012-09-18 08:57:04 -07002424 ObjectArray<AbstractMethod>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04002425 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002426 AbstractMethod* proxy_constructor = proxy_direct_methods->Get(2);
Ian Rogers466bb252011-10-14 03:29:56 -07002427 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
2428 // code_ too)
Ian Rogers50b35e22012-10-04 10:09:15 -07002429 AbstractMethod* constructor = down_cast<AbstractMethod*>(proxy_constructor->Clone(self));
Ian Rogers466bb252011-10-14 03:29:56 -07002430 // Make this constructor public and fix the class to be our Proxy version
2431 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002432 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08002433 return constructor;
2434}
2435
Mathieu Chartier66f19252012-09-18 08:57:04 -07002436static void CheckProxyConstructor(AbstractMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002437 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07002438 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002439 MethodHelper mh(constructor);
2440 CHECK_STREQ(mh.GetName(), "<init>");
Elliott Hughesba8eee12012-01-24 20:25:24 -08002441 CHECK_EQ(mh.GetSignature(), std::string("(Ljava/lang/reflect/InvocationHandler;)V"));
Ian Rogers466bb252011-10-14 03:29:56 -07002442 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04002443}
2444
Ian Rogers50b35e22012-10-04 10:09:15 -07002445AbstractMethod* ClassLinker::CreateProxyMethod(Thread* self, SirtRef<Class>& klass,
2446 SirtRef<AbstractMethod>& prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002447 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
2448 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08002449 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
2450 prototype.get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002451 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07002452 // as necessary
Ian Rogers50b35e22012-10-04 10:09:15 -07002453 AbstractMethod* method = down_cast<AbstractMethod*>(prototype->Clone(self));
Ian Rogers466bb252011-10-14 03:29:56 -07002454
2455 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
2456 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002457 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07002458 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002459
Ian Rogers466bb252011-10-14 03:29:56 -07002460 // At runtime the method looks like a reference and argument saving method, clone the code
2461 // related parameters from this method.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002462 AbstractMethod* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Ian Rogers466bb252011-10-14 03:29:56 -07002463 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
2464 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
2465 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
TDYa1275bb86012012-04-11 05:57:28 -07002466#if !defined(ART_USE_LLVM_COMPILER)
Ian Rogers466bb252011-10-14 03:29:56 -07002467 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
TDYa1275bb86012012-04-11 05:57:28 -07002468#else
Logan Chien7a2a23a2012-06-06 11:01:00 +08002469 OatFile::OatMethod oat_method = GetOatMethodFor(prototype.get());
2470 method->SetCode(oat_method.GetProxyStub());
TDYa1275bb86012012-04-11 05:57:28 -07002471#endif
Ian Rogers16f93672012-02-14 12:29:06 -08002472
Ian Rogersc2b44472011-12-14 21:17:17 -08002473 return method;
2474}
Jesse Wilson95caa792011-10-12 18:14:17 -04002475
Mathieu Chartier66f19252012-09-18 08:57:04 -07002476static void CheckProxyMethod(AbstractMethod* method, SirtRef<AbstractMethod>& prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002477 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07002478 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002479 CHECK(!prototype->IsFinal());
2480 CHECK(method->IsFinal());
2481 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08002482
2483 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
2484 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
2485 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
2486 CHECK_EQ(prototype->GetDexCacheResolvedMethods(), method->GetDexCacheResolvedMethods());
2487 CHECK_EQ(prototype->GetDexCacheResolvedTypes(), method->GetDexCacheResolvedTypes());
2488 CHECK_EQ(prototype->GetDexCacheInitializedStaticStorage(),
2489 method->GetDexCacheInitializedStaticStorage());
2490 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
2491
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002492 MethodHelper mh(method);
Ian Rogers19846512012-02-24 11:42:47 -08002493 MethodHelper mh2(prototype.get());
2494 CHECK_STREQ(mh.GetName(), mh2.GetName());
2495 CHECK_STREQ(mh.GetShorty(), mh2.GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07002496 // More complex sanity - via dex cache
Ian Rogers19846512012-02-24 11:42:47 -08002497 CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04002498}
2499
Ian Rogers0045a292012-03-31 21:08:41 -07002500bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit, bool can_init_statics) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002501 CHECK(klass->IsResolved() || klass->IsErroneous())
Ian Rogers9ffb0392012-09-10 11:56:50 -07002502 << PrettyClass(klass) << ": state=" << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002503
Carl Shapirob5573532011-07-12 18:22:59 -07002504 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002505
Mathieu Chartier66f19252012-09-18 08:57:04 -07002506 AbstractMethod* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002507 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002508 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Ian Rogers1f539342012-10-03 21:09:42 -07002509 ObjectLock lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002510
Brian Carlstromd1422f82011-09-28 11:37:09 -07002511 if (klass->GetStatus() == Class::kStatusInitialized) {
2512 return true;
2513 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002514
Brian Carlstromd1422f82011-09-28 11:37:09 -07002515 if (klass->IsErroneous()) {
2516 ThrowEarlierClassFailure(klass);
2517 return false;
2518 }
2519
jeffhaoebe2e0f2012-06-06 15:19:40 -07002520 if (klass->GetStatus() == Class::kStatusResolved ||
2521 klass->GetStatus() == Class::kStatusRetryVerificationAtRuntime) {
jeffhao98eacac2011-09-14 16:11:53 -07002522 VerifyClass(klass);
2523 if (klass->GetStatus() != Class::kStatusVerified) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07002524 if (klass->GetStatus() == Class::kStatusError) {
2525 CHECK(self->IsExceptionPending());
2526 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002527 return false;
2528 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002529 }
2530
Brian Carlstrom25c33252011-09-18 15:58:35 -07002531 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
2532 if (clinit != NULL && !can_run_clinit) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07002533 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified) << PrettyClass(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07002534 // if the class has a <clinit> but we can't run it during compilation,
Ian Rogers1bddec32012-02-04 12:27:34 -08002535 // don't bother going to kStatusInitializing. We return false so that
2536 // sub-classes don't believe this class is initialized.
Ian Rogers19846512012-02-24 11:42:47 -08002537 // Opportunistically link non-static methods, TODO: don't initialize and dirty pages
2538 // in second pass.
Ian Rogers1bddec32012-02-04 12:27:34 -08002539 return false;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002540 }
2541
Brian Carlstromd1422f82011-09-28 11:37:09 -07002542 // If the class is kStatusInitializing, either this thread is
2543 // initializing higher up the stack or another thread has beat us
2544 // to initializing and we need to wait. Either way, this
2545 // invocation of InitializeClass will not be responsible for
2546 // running <clinit> and will return.
2547 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002548 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002549 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002550 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002551 return true;
2552 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002553 // No. That's fine. Wait for another thread to finish initializing.
2554 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002555 }
2556
2557 if (!ValidateSuperClassDescriptors(klass)) {
2558 klass->SetStatus(Class::kStatusError);
Ian Rogers3d1548d2012-09-24 14:08:03 -07002559 lock.NotifyAll();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002560 return false;
2561 }
2562
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002563 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified) << PrettyClass(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002564
Elliott Hughesdcc24742011-09-07 14:02:44 -07002565 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002566 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002567 }
2568
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002569 uint64_t t0 = NanoTime();
2570
Ian Rogers0045a292012-03-31 21:08:41 -07002571 if (!InitializeSuperClass(klass, can_run_clinit, can_init_statics)) {
Ian Rogers1bddec32012-02-04 12:27:34 -08002572 // Super class initialization failed, this can be because we can't run
2573 // super-class class initializers in which case we'll be verified.
2574 // Otherwise this class is erroneous.
2575 if (!can_run_clinit) {
2576 CHECK(klass->IsVerified());
2577 } else {
2578 CHECK(klass->IsErroneous());
2579 }
Ian Rogers3d1548d2012-09-24 14:08:03 -07002580 // Signal to any waiting threads that saw this class as initializing.
Ian Rogers1f539342012-10-03 21:09:42 -07002581 ObjectLock lock(self, klass);
Ian Rogers3d1548d2012-09-24 14:08:03 -07002582 lock.NotifyAll();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002583 return false;
2584 }
2585
Ian Rogers0045a292012-03-31 21:08:41 -07002586 bool has_static_field_initializers = InitializeStaticFields(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002587
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002588 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002589 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002590 }
2591
Ian Rogers19846512012-02-24 11:42:47 -08002592 FixupStaticTrampolines(klass);
2593
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002594 uint64_t t1 = NanoTime();
2595
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002596 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002597 {
Ian Rogers1f539342012-10-03 21:09:42 -07002598 ObjectLock lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002599
2600 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002601 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002602 klass->SetStatus(Class::kStatusError);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002603 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002604 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002605 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2606 RuntimeStats* thread_stats = self->GetStats();
2607 ++global_stats->class_init_count;
2608 ++thread_stats->class_init_count;
2609 global_stats->class_init_time_ns += (t1 - t0);
2610 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogers0045a292012-03-31 21:08:41 -07002611 // Set the class as initialized except if we can't initialize static fields and static field
2612 // initialization is necessary.
2613 if (!can_init_statics && has_static_field_initializers) {
2614 klass->SetStatus(Class::kStatusVerified); // Don't leave class in initializing state.
2615 success = false;
2616 } else {
2617 klass->SetStatus(Class::kStatusInitialized);
2618 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002619 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002620 ClassHelper kh(klass);
2621 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002622 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002623 }
2624 lock.NotifyAll();
2625 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002626 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002627}
2628
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002629bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07002630 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002631 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002632 self->AssertNoPendingException();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002633 lock.Wait();
2634
2635 // When we wake up, repeat the test for init-in-progress. If
2636 // there's an exception pending (only possible if
2637 // "interruptShouldThrow" was set), bail out.
2638 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002639 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002640 klass->SetStatus(Class::kStatusError);
2641 return false;
2642 }
2643 // Spurious wakeup? Go back to waiting.
2644 if (klass->GetStatus() == Class::kStatusInitializing) {
2645 continue;
2646 }
Ian Rogers3d1548d2012-09-24 14:08:03 -07002647 if (klass->GetStatus() == Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
2648 // Compile time initialization failed.
2649 return false;
2650 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002651 if (klass->IsErroneous()) {
2652 // The caller wants an exception, but it was thrown in a
2653 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002654 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002655 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002656 return false;
2657 }
2658 if (klass->IsInitialized()) {
2659 return true;
2660 }
2661 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2662 }
2663 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2664}
2665
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002666bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2667 if (klass->IsInterface()) {
2668 return true;
2669 }
2670 // begin with the methods local to the superclass
2671 if (klass->HasSuperClass() &&
2672 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2673 const Class* super = klass->GetSuperClass();
Ian Rogers595799e2012-01-11 17:32:51 -08002674 for (int i = super->GetVTable()->GetLength() - 1; i >= 0; --i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07002675 const AbstractMethod* method = klass->GetVTable()->Get(i);
Ian Rogers595799e2012-01-11 17:32:51 -08002676 if (method != super->GetVTable()->Get(i) &&
2677 !IsSameMethodSignatureInDifferentClassContexts(method, super, klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002678 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2679 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2680 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002681 return false;
2682 }
2683 }
2684 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002685 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2686 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2687 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002688 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2689 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07002690 const AbstractMethod* method = interface_entry->GetMethodArray()->Get(j);
Ian Rogers595799e2012-01-11 17:32:51 -08002691 if (!IsSameMethodSignatureInDifferentClassContexts(method, interface,
2692 method->GetDeclaringClass())) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002693 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2694 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2695 PrettyMethod(method).c_str(),
2696 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002697 return false;
2698 }
2699 }
2700 }
2701 }
2702 return true;
2703}
2704
Ian Rogers595799e2012-01-11 17:32:51 -08002705// Returns true if classes referenced by the signature of the method are the
2706// same classes in klass1 as they are in klass2.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002707bool ClassLinker::IsSameMethodSignatureInDifferentClassContexts(const AbstractMethod* method,
Ian Rogers595799e2012-01-11 17:32:51 -08002708 const Class* klass1,
2709 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002710 if (klass1 == klass2) {
2711 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002712 }
Ian Rogers4445a7e2012-10-05 17:19:13 -07002713 const DexFile& dex_file = *method->GetDeclaringClass()->GetDexCache()->GetDexFile();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002714 const DexFile::ProtoId& proto_id =
2715 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002716 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2717 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002718 if (descriptor == NULL) {
2719 break;
2720 }
2721 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2722 // Found a non-primitive type.
Ian Rogers595799e2012-01-11 17:32:51 -08002723 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002724 return false;
2725 }
2726 }
2727 }
2728 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002729 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002730 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Ian Rogers595799e2012-01-11 17:32:51 -08002731 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002732 return false;
2733 }
2734 }
2735 return true;
2736}
2737
Ian Rogers595799e2012-01-11 17:32:51 -08002738// Returns true if the descriptor resolves to the same class in the context of klass1 and klass2.
2739bool ClassLinker::IsSameDescriptorInDifferentClassContexts(const char* descriptor,
2740 const Class* klass1,
2741 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002742 CHECK(descriptor != NULL);
2743 CHECK(klass1 != NULL);
2744 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002745 if (klass1 == klass2) {
2746 return true;
2747 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002748 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Ian Rogers595799e2012-01-11 17:32:51 -08002749 if (found1 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002750 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002751 }
Ian Rogers595799e2012-01-11 17:32:51 -08002752 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
2753 if (found2 == NULL) {
2754 Thread::Current()->ClearException();
2755 }
2756 return found1 == found2;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002757}
2758
Ian Rogers0045a292012-03-31 21:08:41 -07002759bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit, bool can_init_fields) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002760 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002761 if (!klass->IsInterface() && klass->HasSuperClass()) {
2762 Class* super_class = klass->GetSuperClass();
Ian Rogers9ffb0392012-09-10 11:56:50 -07002763 if (!super_class->IsInitialized()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002764 CHECK(!super_class->IsInterface());
Ian Rogers1f539342012-10-03 21:09:42 -07002765 // Must hold lock on object when initializing and setting status.
2766 ObjectLock lock(Thread::Current(), klass);
Ian Rogers0045a292012-03-31 21:08:41 -07002767 bool super_initialized = InitializeClass(super_class, can_run_clinit, can_init_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002768 // TODO: check for a pending exception
2769 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002770 if (!can_run_clinit) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002771 // Don't set status to error when we can't run <clinit>.
2772 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing) << PrettyClass(klass);
2773 klass->SetStatus(Class::kStatusVerified);
2774 return false;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002775 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002776 klass->SetStatus(Class::kStatusError);
2777 klass->NotifyAll();
2778 return false;
2779 }
2780 }
2781 }
2782 return true;
2783}
2784
Ian Rogers0045a292012-03-31 21:08:41 -07002785bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit, bool can_init_fields) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002786 CHECK(c != NULL);
2787 if (c->IsInitialized()) {
2788 return true;
2789 }
2790
Elliott Hughes5f791332011-09-15 17:45:30 -07002791 Thread* self = Thread::Current();
Elliott Hughes34e06962012-04-09 13:55:55 -07002792 ScopedThreadStateChange tsc(self, kRunnable);
Ian Rogers0045a292012-03-31 21:08:41 -07002793 bool success = InitializeClass(c, can_run_clinit, can_init_fields);
Ian Rogers595799e2012-01-11 17:32:51 -08002794 if (!success) {
Ian Rogers1bddec32012-02-04 12:27:34 -08002795 CHECK(self->IsExceptionPending() || !can_run_clinit) << PrettyClass(c);
Ian Rogers595799e2012-01-11 17:32:51 -08002796 }
2797 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002798}
2799
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002800void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Elliott Hughesa0e18062012-04-13 15:59:59 -07002801 Class* c, SafeMap<uint32_t, Field*>& field_map) {
Ian Rogers365c1022012-06-22 15:05:28 -07002802 ClassLoader* cl = c->GetClassLoader();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002803 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002804 ClassDataItemIterator it(dex_file, class_data);
2805 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002806 field_map.Put(i, ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true));
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002807 }
2808}
2809
Ian Rogers0045a292012-03-31 21:08:41 -07002810bool ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002811 size_t num_static_fields = klass->NumStaticFields();
2812 if (num_static_fields == 0) {
Ian Rogers0045a292012-03-31 21:08:41 -07002813 return false;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002814 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002815 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002816 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002817 if (dex_cache == NULL) {
Ian Rogers0045a292012-03-31 21:08:41 -07002818 return false;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002819 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002820 ClassHelper kh(klass);
2821 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002822 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002823 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002824 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002825
Ian Rogers0571d352011-11-03 19:51:38 -07002826 if (it.HasNext()) {
2827 // 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 -07002828 SafeMap<uint32_t, Field*> field_map;
Ian Rogers0571d352011-11-03 19:51:38 -07002829 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2830 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
Elliott Hughesa0e18062012-04-13 15:59:59 -07002831 it.ReadValueToField(field_map.Get(i));
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002832 }
Ian Rogers0045a292012-03-31 21:08:41 -07002833 return true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002834 }
Ian Rogers0045a292012-03-31 21:08:41 -07002835 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002836}
2837
Ian Rogersc2b44472011-12-14 21:17:17 -08002838bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002839 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002840 if (!LinkSuperClass(klass)) {
2841 return false;
2842 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002843 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002844 return false;
2845 }
2846 if (!LinkInstanceFields(klass)) {
2847 return false;
2848 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002849 if (!LinkStaticFields(klass)) {
2850 return false;
2851 }
2852 CreateReferenceInstanceOffsets(klass);
2853 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002854 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2855 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002856 return true;
2857}
2858
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002859bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002860 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002861 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2862 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
Ian Rogerscab01012012-01-10 17:35:46 -08002863 CHECK(class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002864 uint16_t super_class_idx = class_def->superclass_idx_;
2865 if (super_class_idx != DexFile::kDexNoIndex16) {
2866 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002867 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002868 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002869 return false;
2870 }
Ian Rogersbe125a92012-01-11 15:19:49 -08002871 // Verify
2872 if (!klass->CanAccess(super_class)) {
2873 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2874 "Class %s extended by class %s is inaccessible",
2875 PrettyDescriptor(super_class).c_str(),
2876 PrettyDescriptor(klass.get()).c_str());
2877 return false;
2878 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002879 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002880 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002881 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2882 if (interfaces != NULL) {
2883 for (size_t i = 0; i < interfaces->Size(); i++) {
2884 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2885 Class* interface = ResolveType(dex_file, idx, klass.get());
2886 if (interface == NULL) {
2887 DCHECK(Thread::Current()->IsExceptionPending());
2888 return false;
2889 }
2890 // Verify
2891 if (!klass->CanAccess(interface)) {
2892 // TODO: the RI seemed to ignore this in my testing.
2893 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2894 "Interface %s implemented by class %s is inaccessible",
2895 PrettyDescriptor(interface).c_str(),
2896 PrettyDescriptor(klass.get()).c_str());
2897 return false;
2898 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002899 }
2900 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002901 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002902 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002903 return true;
2904}
2905
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002906bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002907 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002908 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002909 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002910 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002911 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002912 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002913 return false;
2914 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002915 return true;
2916 }
2917 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002918 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002919 return false;
2920 }
2921 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002922 if (super->IsFinal() || super->IsInterface()) {
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08002923 Thread* self = Thread::Current();
2924 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002925 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002926 PrettyDescriptor(super).c_str(),
2927 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002928 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002929 return false;
2930 }
2931 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002932 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002933 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002934 PrettyDescriptor(super).c_str(),
2935 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002936 return false;
2937 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002938
2939 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2940 if (super->IsFinalizable()) {
2941 klass->SetFinalizable();
2942 }
2943
Elliott Hughes2da50362011-10-10 16:57:08 -07002944 // Inherit reference flags (if any) from the superclass.
2945 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2946 if (reference_flags != 0) {
2947 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2948 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002949 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002950 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002951 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002952 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002953 return false;
2954 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002955
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002956#ifndef NDEBUG
2957 // Ensure super classes are fully resolved prior to resolving fields..
2958 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002959 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002960 super = super->GetSuperClass();
2961 }
2962#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002963 return true;
2964}
2965
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002966// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002967bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002968 if (klass->IsInterface()) {
2969 // No vtable.
2970 size_t count = klass->NumVirtualMethods();
2971 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002972 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002973 return false;
2974 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002975 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002976 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002977 }
jeffhaobdb76512011-09-07 11:43:16 -07002978 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002979 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002980 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002981 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002982 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002983 }
2984 return true;
2985}
2986
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002987bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Ian Rogers1f539342012-10-03 21:09:42 -07002988 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002989 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002990 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2991 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002992 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002993 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers1f539342012-10-03 21:09:42 -07002994 SirtRef<ObjectArray<AbstractMethod> >
Ian Rogers50b35e22012-10-04 10:09:15 -07002995 vtable(self, klass->GetSuperClass()->GetVTable()->CopyOf(self, max_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002996 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002997 MethodHelper local_mh(NULL, this);
2998 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002999 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003000 AbstractMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003001 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003002 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07003003 for (; j < actual_count; ++j) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003004 AbstractMethod* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003005 super_mh.ChangeMethod(super_method);
Elliott Hughes39717372012-07-13 16:21:23 -07003006 if (local_mh.HasSameNameAndSignature(&super_mh)) {
3007 if (klass->CanAccessMember(super_method->GetDeclaringClass(), super_method->GetAccessFlags())) {
3008 if (super_method->IsFinal()) {
3009 ThrowLinkageError("Method %s overrides final method in class %s",
3010 PrettyMethod(local_method).c_str(),
3011 super_mh.GetDeclaringClassDescriptor());
3012 return false;
3013 }
3014 vtable->Set(j, local_method);
3015 local_method->SetMethodIndex(j);
3016 break;
3017 } else {
3018 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method)
3019 << " would have incorrectly overridden the package-private method in "
3020 << PrettyDescriptor(super_mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003021 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003022 }
3023 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07003024 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003025 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003026 vtable->Set(actual_count, local_method);
3027 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003028 actual_count += 1;
3029 }
3030 }
3031 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08003032 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003033 return false;
3034 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003035 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003036 CHECK_LE(actual_count, max_count);
3037 if (actual_count < max_count) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003038 vtable.reset(vtable->CopyOf(self, actual_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003039 }
Ian Rogers30fab402012-01-23 15:43:46 -08003040 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003041 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003042 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07003043 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07003044 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07003045 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003046 return false;
3047 }
Ian Rogers1f539342012-10-03 21:09:42 -07003048 SirtRef<ObjectArray<AbstractMethod> >
Ian Rogers4445a7e2012-10-05 17:19:13 -07003049 vtable(self, AllocMethodArray(self, num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07003050 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003051 AbstractMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003052 vtable->Set(i, virtual_method);
3053 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003054 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003055 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003056 }
3057 return true;
3058}
3059
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003060bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003061 size_t super_ifcount;
3062 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003063 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003064 } else {
3065 super_ifcount = 0;
3066 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07003067 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003068 ClassHelper kh(klass.get(), this);
Ian Rogersd24e2642012-06-06 21:21:43 -07003069 uint32_t num_interfaces = interfaces == NULL ? kh.NumDirectInterfaces() : interfaces->GetLength();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003070 ifcount += num_interfaces;
3071 for (size_t i = 0; i < num_interfaces; i++) {
Ian Rogersd24e2642012-06-06 21:21:43 -07003072 Class* interface = interfaces == NULL ? kh.GetDirectInterface(i) : interfaces->Get(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003073 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003074 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07003075 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003076 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07003077 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003078 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003079 return true;
3080 }
Ian Rogers1f539342012-10-03 21:09:42 -07003081 Thread* self = Thread::Current();
Ian Rogers50b35e22012-10-04 10:09:15 -07003082 SirtRef<ObjectArray<InterfaceEntry> > iftable(self, AllocIfTable(self, ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003083 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003084 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
3085 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogersb52b01a2012-01-12 17:01:38 -08003086 Class* super_interface = super_iftable->Get(i)->GetInterface();
Ian Rogers50b35e22012-10-04 10:09:15 -07003087 iftable->Set(i, AllocInterfaceEntry(self, super_interface));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003088 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003089 }
3090 // Flatten the interface inheritance hierarchy.
3091 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003092 for (size_t i = 0; i < num_interfaces; i++) {
Ian Rogersd24e2642012-06-06 21:21:43 -07003093 Class* interface = interfaces == NULL ? kh.GetDirectInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003094 DCHECK(interface != NULL);
3095 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003096 ClassHelper ih(interface);
Brian Carlstrom4d9716c2012-01-30 01:49:33 -08003097 self->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003098 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003099 PrettyDescriptor(klass.get()).c_str(),
3100 PrettyDescriptor(ih.GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003101 return false;
3102 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08003103 // Check if interface is already in iftable
3104 bool duplicate = false;
3105 for (size_t j = 0; j < idx; j++) {
3106 Class* existing_interface = iftable->Get(j)->GetInterface();
3107 if (existing_interface == interface) {
3108 duplicate = true;
3109 break;
3110 }
3111 }
3112 if (!duplicate) {
3113 // Add this non-duplicate interface.
Ian Rogers50b35e22012-10-04 10:09:15 -07003114 iftable->Set(idx++, AllocInterfaceEntry(self, interface));
Ian Rogersb52b01a2012-01-12 17:01:38 -08003115 // Add this interface's non-duplicate super-interfaces.
3116 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
3117 Class* super_interface = interface->GetIfTable()->Get(j)->GetInterface();
3118 bool super_duplicate = false;
3119 for (size_t k = 0; k < idx; k++) {
3120 Class* existing_interface = iftable->Get(k)->GetInterface();
3121 if (existing_interface == super_interface) {
3122 super_duplicate = true;
3123 break;
3124 }
3125 }
3126 if (!super_duplicate) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003127 iftable->Set(idx++, AllocInterfaceEntry(self, super_interface));
Ian Rogersb52b01a2012-01-12 17:01:38 -08003128 }
3129 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003130 }
3131 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08003132 // Shrink iftable in case duplicates were found
3133 if (idx < ifcount) {
Ian Rogers50b35e22012-10-04 10:09:15 -07003134 iftable.reset(iftable->CopyOf(self, idx));
Ian Rogersb52b01a2012-01-12 17:01:38 -08003135 ifcount = idx;
3136 } else {
3137 CHECK_EQ(idx, ifcount);
3138 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003139 klass->SetIfTable(iftable.get());
Elliott Hughes4681c802011-09-25 18:04:37 -07003140
3141 // If we're an interface, we don't need the vtable pointers, so we're done.
3142 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003143 return true;
3144 }
Mathieu Chartier66f19252012-09-18 08:57:04 -07003145 std::vector<AbstractMethod*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003146 MethodHelper vtable_mh(NULL, this);
3147 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003148 for (size_t i = 0; i < ifcount; ++i) {
3149 InterfaceEntry* interface_entry = iftable->Get(i);
3150 Class* interface = interface_entry->GetInterface();
Ian Rogers50b35e22012-10-04 10:09:15 -07003151 ObjectArray<AbstractMethod>* method_array =
Ian Rogers4445a7e2012-10-05 17:19:13 -07003152 AllocMethodArray(self, interface->NumVirtualMethods());
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003153 interface_entry->SetMethodArray(method_array);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003154 ObjectArray<AbstractMethod>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003155 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003156 AbstractMethod* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003157 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003158 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07003159 // For each method listed in the interface's method list, find the
3160 // matching method in our class's method list. We want to favor the
3161 // subclass over the superclass, which just requires walking
3162 // back from the end of the vtable. (This only matters if the
3163 // superclass defines a private method and this class redefines
3164 // it -- otherwise it would use the same vtable slot. In .dex files
3165 // those don't end up in the virtual method table, so it shouldn't
3166 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003167 for (k = vtable->GetLength() - 1; k >= 0; --k) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003168 AbstractMethod* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003169 vtable_mh.ChangeMethod(vtable_method);
3170 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07003171 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07003172 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003173 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003174 return false;
3175 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003176 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003177 break;
3178 }
3179 }
3180 if (k < 0) {
Ian Rogers1f539342012-10-03 21:09:42 -07003181 SirtRef<AbstractMethod> miranda_method(self, NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07003182 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003183 AbstractMethod* mir_method = miranda_list[mir];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003184 vtable_mh.ChangeMethod(mir_method);
3185 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003186 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003187 break;
3188 }
3189 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003190 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07003191 // point the interface table at a phantom slot
Ian Rogers50b35e22012-10-04 10:09:15 -07003192 miranda_method.reset(down_cast<AbstractMethod*>(interface_method->Clone(self)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003193 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003194 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003195 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003196 }
3197 }
3198 }
Elliott Hughes4681c802011-09-25 18:04:37 -07003199 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07003200 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07003201 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07003202 klass->SetVirtualMethods((old_method_count == 0)
Ian Rogers4445a7e2012-10-05 17:19:13 -07003203 ? AllocMethodArray(self, new_method_count)
Ian Rogers50b35e22012-10-04 10:09:15 -07003204 : klass->GetVirtualMethods()->CopyOf(self, new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003205
Ian Rogers1f539342012-10-03 21:09:42 -07003206 SirtRef<ObjectArray<AbstractMethod> > vtable(self, klass->GetVTableDuringLinking());
Ian Rogers30fab402012-01-23 15:43:46 -08003207 CHECK(vtable.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003208 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07003209 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers50b35e22012-10-04 10:09:15 -07003210 vtable.reset(vtable->CopyOf(self, new_vtable_count));
Elliott Hughes4681c802011-09-25 18:04:37 -07003211 for (size_t i = 0; i < miranda_list.size(); ++i) {
Mathieu Chartier66f19252012-09-18 08:57:04 -07003212 AbstractMethod* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07003213 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07003214 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
3215 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
3216 klass->SetVirtualMethod(old_method_count + i, method);
3217 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003218 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003219 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08003220 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003221 }
Elliott Hughes4681c802011-09-25 18:04:37 -07003222
Mathieu Chartier66f19252012-09-18 08:57:04 -07003223 ObjectArray<AbstractMethod>* vtable = klass->GetVTableDuringLinking();
Elliott Hughes4681c802011-09-25 18:04:37 -07003224 for (int i = 0; i < vtable->GetLength(); ++i) {
3225 CHECK(vtable->Get(i) != NULL);
3226 }
3227
3228// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
3229
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003230 return true;
3231}
3232
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003233bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
3234 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003235 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003236}
3237
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003238bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
3239 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003240 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003241 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003242 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07003243 return success;
3244}
3245
Brian Carlstromdbc05252011-09-09 01:59:59 -07003246struct LinkFieldsComparator {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003247 explicit LinkFieldsComparator(FieldHelper* fh)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003248 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003249 : fh_(fh) {}
3250 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
3251 bool operator()(const Field* field1, const Field* field2) NO_THREAD_SAFETY_ANALYSIS {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003252 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003253 fh_->ChangeField(field1);
3254 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
3255 fh_->ChangeField(field2);
3256 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003257 bool isPrimitive1 = type1 != Primitive::kPrimNot;
3258 bool isPrimitive2 = type2 != Primitive::kPrimNot;
3259 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
3260 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003261 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
3262 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
3263 if (order1 != order2) {
3264 return order1 < order2;
3265 }
3266
3267 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003268 fh_->ChangeField(field1);
3269 StringPiece name1(fh_->GetName());
3270 fh_->ChangeField(field2);
3271 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07003272 return name1 < name2;
3273 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003274
3275 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07003276};
3277
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003278bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003279 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003280 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003281
3282 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003283 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003284
3285 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07003286 size_t size;
3287 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003288 if (is_static) {
3289 size = klass->GetClassSize();
3290 field_offset = Class::FieldsOffset();
3291 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003292 Class* super_class = klass->GetSuperClass();
3293 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07003294 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003295 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003296 }
3297 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003298 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003299
Brian Carlstromdbc05252011-09-09 01:59:59 -07003300 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003301
Brian Carlstromdbc05252011-09-09 01:59:59 -07003302 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07003303 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07003304 std::deque<Field*> grouped_and_sorted_fields;
3305 for (size_t i = 0; i < num_fields; i++) {
3306 grouped_and_sorted_fields.push_back(fields->Get(i));
3307 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003308 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003309 std::sort(grouped_and_sorted_fields.begin(),
3310 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003311 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07003312
3313 // References should be at the front.
3314 size_t current_field = 0;
3315 size_t num_reference_fields = 0;
3316 for (; current_field < num_fields; current_field++) {
3317 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003318 fh.ChangeField(field);
3319 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003320 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07003321 if (isPrimitive) {
3322 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003323 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07003324 grouped_and_sorted_fields.pop_front();
3325 num_reference_fields++;
3326 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003327 field->SetOffset(field_offset);
3328 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003329 }
3330
3331 // Now we want to pack all of the double-wide fields together. If
3332 // we're not aligned, though, we want to shuffle one 32-bit field
3333 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07003334 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003335 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
3336 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003337 fh.ChangeField(field);
3338 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003339 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
3340 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07003341 continue;
3342 }
3343 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003344 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003345 // drop the consumed field
3346 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
3347 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003348 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07003349 // whether we found a 32-bit field for padding or not, we advance
3350 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003351 }
3352
3353 // Alignment is good, shuffle any double-wide fields forward, and
3354 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07003355 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07003356 while (!grouped_and_sorted_fields.empty()) {
3357 Field* field = grouped_and_sorted_fields.front();
3358 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003359 fh.ChangeField(field);
3360 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003361 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07003362 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003363 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003364 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003365 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07003366 ? sizeof(uint64_t)
3367 : sizeof(uint32_t)));
3368 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003369 }
3370
Elliott Hughesadb460d2011-10-05 17:02:34 -07003371 // 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 -08003372 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
3373 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07003374 // We know there are no non-reference fields in the Reference classes, and we know
3375 // that 'referent' is alphabetically last, so this is easy...
3376 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003377 fh.ChangeField(fields->Get(num_fields - 1));
Elliott Hughesba8eee12012-01-24 20:25:24 -08003378 CHECK_STREQ(fh.GetName(), "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07003379 --num_reference_fields;
3380 }
3381
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003382#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07003383 // Make sure that all reference fields appear before
3384 // non-reference fields, and all double-wide fields are aligned.
3385 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07003386 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003387 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003388 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003389 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003390 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07003391 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07003392 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
3393 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003394 fh.ChangeField(field);
3395 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003396 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003397 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07003398 is_primitive = true; // We lied above, so we have to expect a lie here.
3399 }
3400 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07003401 if (!seen_non_ref) {
3402 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003403 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003404 }
Brian Carlstrombe977852011-07-19 14:54:54 -07003405 } else {
3406 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003407 }
3408 }
Brian Carlstrombe977852011-07-19 14:54:54 -07003409 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003410 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003411 }
3412#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003413 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003414 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003415 if (is_static) {
3416 klass->SetNumReferenceStaticFields(num_reference_fields);
3417 klass->SetClassSize(size);
3418 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003419 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07003420 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003421 klass->SetObjectSize(size);
3422 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003423 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003424 return true;
3425}
3426
3427// Set the bitmap of reference offsets, refOffsets, from the ifields
3428// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003429void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003430 uint32_t reference_offsets = 0;
3431 Class* super_class = klass->GetSuperClass();
3432 if (super_class != NULL) {
3433 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003434 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003435 if (reference_offsets == CLASS_WALK_SUPER) {
3436 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003437 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003438 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003439 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003440 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003441}
3442
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003443void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003444 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003445}
3446
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003447void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003448 uint32_t reference_offsets) {
3449 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003450 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
3451 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003452 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003453 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003454 // All of the fields that contain object references are guaranteed
3455 // to be at the beginning of the fields list.
3456 for (size_t i = 0; i < num_reference_fields; ++i) {
3457 // Note that byte_offset is the offset from the beginning of
3458 // object, not the offset into instance data
3459 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003460 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003461 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
3462 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
3463 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07003464 CHECK_NE(new_bit, 0U);
3465 reference_offsets |= new_bit;
3466 } else {
3467 reference_offsets = CLASS_WALK_SUPER;
3468 break;
3469 }
3470 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003471 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003472 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003473 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003474 } else {
3475 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003476 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003477}
3478
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003479String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07003480 uint32_t string_idx, DexCache* dex_cache) {
Brian Carlstrom7d776242012-03-06 23:05:49 -08003481 DCHECK(dex_cache != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003482 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003483 if (resolved != NULL) {
3484 return resolved;
3485 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003486 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
3487 int32_t utf16_length = dex_file.GetStringLength(string_id);
3488 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07003489 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003490 dex_cache->SetResolvedString(string_idx, string);
3491 return string;
3492}
3493
3494Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003495 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003496 DexCache* dex_cache,
Ian Rogers365c1022012-06-22 15:05:28 -07003497 ClassLoader* class_loader) {
Brian Carlstrom7d776242012-03-06 23:05:49 -08003498 DCHECK(dex_cache != NULL);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003499 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003500 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07003501 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003502 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003503 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05003504 // TODO: we used to throw here if resolved's class loader was not the
3505 // boot class loader. This was to permit different classes with the
3506 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003507 dex_cache->SetResolvedType(type_idx, resolved);
3508 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08003509 CHECK(Thread::Current()->IsExceptionPending())
3510 << "Expected pending exception for failed resolution of: " << descriptor;
jeffhao8cd6dda2012-02-22 10:15:34 -08003511 // Convert a ClassNotFoundException to a NoClassDefFoundError
3512 if (Thread::Current()->GetException()->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
3513 Thread::Current()->ClearException();
3514 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
3515 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003516 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003517 }
3518 return resolved;
3519}
3520
Mathieu Chartier66f19252012-09-18 08:57:04 -07003521AbstractMethod* ClassLinker::ResolveMethod(const DexFile& dex_file,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003522 uint32_t method_idx,
3523 DexCache* dex_cache,
Ian Rogers365c1022012-06-22 15:05:28 -07003524 ClassLoader* class_loader,
Mathieu Chartier66f19252012-09-18 08:57:04 -07003525 const AbstractMethod* referrer,
Ian Rogers08f753d2012-08-24 14:35:25 -07003526 InvokeType type) {
Brian Carlstrom7d776242012-03-06 23:05:49 -08003527 DCHECK(dex_cache != NULL);
Ian Rogers08f753d2012-08-24 14:35:25 -07003528 // Check for hit in the dex cache.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003529 AbstractMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003530 if (resolved != NULL) {
3531 return resolved;
3532 }
Ian Rogers08f753d2012-08-24 14:35:25 -07003533 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003534 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3535 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
3536 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07003537 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003538 return NULL;
3539 }
Ian Rogers08f753d2012-08-24 14:35:25 -07003540 // Scan using method_idx, this saves string compares but will only hit for matching dex
3541 // caches/files.
3542 switch (type) {
3543 case kDirect: // Fall-through.
3544 case kStatic:
3545 resolved = klass->FindDirectMethod(dex_cache, method_idx);
3546 break;
3547 case kInterface:
3548 resolved = klass->FindInterfaceMethod(dex_cache, method_idx);
3549 break;
3550 case kSuper: // Fall-through.
3551 case kVirtual:
3552 resolved = klass->FindVirtualMethod(dex_cache, method_idx);
3553 break;
3554 default:
3555 LOG(FATAL) << "Unreachable - invocation type: " << type;
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003556 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003557 if (resolved == NULL) {
Ian Rogers08f753d2012-08-24 14:35:25 -07003558 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003559 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
3560 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Ian Rogers08f753d2012-08-24 14:35:25 -07003561 switch (type) {
3562 case kDirect: // Fall-through.
3563 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08003564 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07003565 break;
3566 case kInterface:
3567 resolved = klass->FindInterfaceMethod(name, signature);
3568 break;
3569 case kSuper: // Fall-through.
3570 case kVirtual:
3571 resolved = klass->FindVirtualMethod(name, signature);
3572 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003573 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003574 }
Ian Rogers08f753d2012-08-24 14:35:25 -07003575 if (resolved != NULL) {
3576 // We found a method, check for incompatible class changes.
Ian Rogers87e552d2012-08-31 15:54:48 -07003577 if (resolved->CheckIncompatibleClassChange(type)) {
3578 resolved = NULL;
Ian Rogers08f753d2012-08-24 14:35:25 -07003579 }
3580 }
3581 if (resolved != NULL) {
3582 // Be a good citizen and update the dex cache to speed subsequent calls.
3583 dex_cache->SetResolvedMethod(method_idx, resolved);
3584 return resolved;
3585 } else {
jeffhaoc0228b82012-08-29 18:15:05 -07003586 // We failed to find the method which means either an access error, an incompatible class
3587 // change, or no such method. First try to find the method among direct and virtual methods.
Ian Rogers08f753d2012-08-24 14:35:25 -07003588 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
3589 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
3590 switch (type) {
3591 case kDirect:
3592 case kStatic:
3593 resolved = klass->FindVirtualMethod(name, signature);
jeffhaoc0228b82012-08-29 18:15:05 -07003594 break;
3595 case kInterface:
3596 case kVirtual:
3597 case kSuper:
3598 resolved = klass->FindDirectMethod(name, signature);
3599 break;
3600 }
3601
3602 // If we found something, check that it can be accessed by the referrer.
3603 if (resolved != NULL && referrer != NULL) {
3604 Class* methods_class = resolved->GetDeclaringClass();
3605 Class* referring_class = referrer->GetDeclaringClass();
3606 if (!referring_class->CanAccess(methods_class)) {
Ian Rogers87e552d2012-08-31 15:54:48 -07003607 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
3608 referrer, resolved, type);
jeffhaoc0228b82012-08-29 18:15:05 -07003609 return NULL;
3610 } else if (!referring_class->CanAccessMember(methods_class,
3611 resolved->GetAccessFlags())) {
Ian Rogers87e552d2012-08-31 15:54:48 -07003612 ThrowIllegalAccessErrorMethod(referring_class, resolved);
jeffhaoc0228b82012-08-29 18:15:05 -07003613 return NULL;
3614 }
3615 }
3616
3617 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
3618 // methods and throw if we find the method there. If we find nothing, throw a NoSuchMethodError.
3619 switch (type) {
3620 case kDirect:
3621 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07003622 if (resolved != NULL) {
Ian Rogers2fc14272012-08-30 10:56:57 -07003623 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003624 } else {
3625 resolved = klass->FindInterfaceMethod(name, signature);
3626 if (resolved != NULL) {
Ian Rogers2fc14272012-08-30 10:56:57 -07003627 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003628 } else {
Ian Rogers2fc14272012-08-30 10:56:57 -07003629 ThrowNoSuchMethodError(type, klass, name, signature, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003630 }
3631 }
3632 break;
3633 case kInterface:
Ian Rogers08f753d2012-08-24 14:35:25 -07003634 if (resolved != NULL) {
Ian Rogers2fc14272012-08-30 10:56:57 -07003635 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003636 } else {
3637 resolved = klass->FindVirtualMethod(name, signature);
3638 if (resolved != NULL) {
Ian Rogers2fc14272012-08-30 10:56:57 -07003639 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003640 } else {
Ian Rogers2fc14272012-08-30 10:56:57 -07003641 ThrowNoSuchMethodError(type, klass, name, signature, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003642 }
3643 }
3644 break;
3645 case kSuper:
Ian Rogers2fc14272012-08-30 10:56:57 -07003646 ThrowNoSuchMethodError(type, klass, name, signature, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003647 break;
3648 case kVirtual:
Ian Rogers08f753d2012-08-24 14:35:25 -07003649 if (resolved != NULL) {
Ian Rogers2fc14272012-08-30 10:56:57 -07003650 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003651 } else {
3652 resolved = klass->FindInterfaceMethod(name, signature);
3653 if (resolved != NULL) {
Ian Rogers2fc14272012-08-30 10:56:57 -07003654 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003655 } else {
Ian Rogers2fc14272012-08-30 10:56:57 -07003656 ThrowNoSuchMethodError(type, klass, name, signature, referrer);
Ian Rogers08f753d2012-08-24 14:35:25 -07003657 }
3658 }
3659 break;
3660 }
3661 DCHECK(Thread::Current()->IsExceptionPending());
3662 return NULL;
3663 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003664}
3665
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003666Field* ClassLinker::ResolveField(const DexFile& dex_file,
3667 uint32_t field_idx,
3668 DexCache* dex_cache,
Ian Rogers365c1022012-06-22 15:05:28 -07003669 ClassLoader* class_loader,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003670 bool is_static) {
Brian Carlstrom7d776242012-03-06 23:05:49 -08003671 DCHECK(dex_cache != NULL);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003672 Field* resolved = dex_cache->GetResolvedField(field_idx);
3673 if (resolved != NULL) {
3674 return resolved;
3675 }
3676 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3677 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3678 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003679 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003680 return NULL;
3681 }
3682
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003683 if (is_static) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003684 resolved = klass->FindStaticField(dex_cache, field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003685 } else {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003686 resolved = klass->FindInstanceField(dex_cache, field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003687 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003688
3689 if (resolved == NULL) {
3690 const char* name = dex_file.GetFieldName(field_id);
3691 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3692 if (is_static) {
3693 resolved = klass->FindStaticField(name, type);
3694 } else {
3695 resolved = klass->FindInstanceField(name, type);
3696 }
3697 if (resolved == NULL) {
3698 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
3699 return NULL;
3700 }
Ian Rogersb067ac22011-12-13 18:05:09 -08003701 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08003702 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08003703 return resolved;
3704}
3705
3706Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
3707 uint32_t field_idx,
3708 DexCache* dex_cache,
Ian Rogers365c1022012-06-22 15:05:28 -07003709 ClassLoader* class_loader) {
Brian Carlstrom7d776242012-03-06 23:05:49 -08003710 DCHECK(dex_cache != NULL);
Ian Rogersb067ac22011-12-13 18:05:09 -08003711 Field* resolved = dex_cache->GetResolvedField(field_idx);
3712 if (resolved != NULL) {
3713 return resolved;
3714 }
3715 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3716 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3717 if (klass == NULL) {
3718 DCHECK(Thread::Current()->IsExceptionPending());
3719 return NULL;
3720 }
3721
3722 const char* name = dex_file.GetFieldName(field_id);
3723 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3724 resolved = klass->FindField(name, type);
3725 if (resolved != NULL) {
3726 dex_cache->SetResolvedField(field_idx, resolved);
3727 } else {
3728 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003729 }
3730 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07003731}
3732
Mathieu Chartier66f19252012-09-18 08:57:04 -07003733const char* ClassLinker::MethodShorty(uint32_t method_idx, AbstractMethod* referrer, uint32_t* length) {
Ian Rogersad25ac52011-10-04 19:13:33 -07003734 Class* declaring_class = referrer->GetDeclaringClass();
3735 DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07003736 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07003737 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08003738 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07003739}
3740
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003741void ClassLinker::DumpAllClasses(int flags) const {
3742 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3743 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3744 std::vector<Class*> all_classes;
3745 {
Ian Rogers50b35e22012-10-04 10:09:15 -07003746 MutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003747 typedef Table::const_iterator It; // TODO: C++0x auto
3748 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3749 all_classes.push_back(it->second);
3750 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003751 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3752 all_classes.push_back(it->second);
3753 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003754 }
3755
3756 for (size_t i = 0; i < all_classes.size(); ++i) {
3757 all_classes[i]->DumpClass(std::cerr, flags);
3758 }
3759}
3760
Elliott Hughescac6cc72011-11-03 20:31:21 -07003761void ClassLinker::DumpForSigQuit(std::ostream& os) const {
Ian Rogers50b35e22012-10-04 10:09:15 -07003762 MutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Elliott Hughescac6cc72011-11-03 20:31:21 -07003763 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3764 << classes_.size() << " allocated classes\n";
3765}
3766
Elliott Hughese27955c2011-08-26 15:21:24 -07003767size_t ClassLinker::NumLoadedClasses() const {
Ian Rogers50b35e22012-10-04 10:09:15 -07003768 MutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003769 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003770}
3771
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003772pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07003773 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003774}
3775
3776pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003777 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003778}
3779
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003780void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3781 DCHECK(!init_done_);
3782
3783 DCHECK(klass != NULL);
3784 DCHECK(klass->GetClassLoader() == NULL);
3785
3786 DCHECK(class_roots_ != NULL);
3787 DCHECK(class_roots_->Get(class_root) == NULL);
3788 class_roots_->Set(class_root, klass);
3789}
3790
Logan Chien0c717dd2012-03-28 18:31:07 +08003791void ClassLinker::RelocateExecutable() {
Ian Rogers50b35e22012-10-04 10:09:15 -07003792 MutexLock mu(Thread::Current(), dex_lock_);
Logan Chien0c717dd2012-03-28 18:31:07 +08003793 for (size_t i = 0; i < oat_files_.size(); ++i) {
3794 const_cast<OatFile*>(oat_files_[i])->RelocateExecutable();
3795 }
3796}
3797
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003798} // namespace art