blob: 4362b8249fc660179aec348c97e71dd93384fcb6 [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 Carlstromdbc05252011-09-09 01:59:59 -070022#include <deque>
Ian Rogers700a4022014-05-19 16:49:03 -070023#include <memory>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070024#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070025#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070026#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070027
Elliott Hughes1aa246d2012-12-13 09:29:36 -080028#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080029#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010030#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080031#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080032#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080033#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000034#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080035#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070036#include "dex_file-inl.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070037#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070038#include "gc/accounting/card_table-inl.h"
39#include "gc/accounting/heap_bitmap.h"
40#include "gc/heap.h"
41#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070042#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070043#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070044#include "interpreter/interpreter.h"
Ian Rogers0571d352011-11-03 19:51:38 -070045#include "leb128.h"
Ian Rogerscb6b0f32014-08-12 02:30:58 -070046#include "method_helper-inl.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080047#include "oat.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070048#include "oat_file.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070049#include "object_lock.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070050#include "mirror/art_field-inl.h"
51#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "mirror/class.h"
53#include "mirror/class-inl.h"
54#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070055#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056#include "mirror/iftable-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057#include "mirror/object-inl.h"
58#include "mirror/object_array-inl.h"
59#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070060#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080061#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070062#include "mirror/string-inl.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080063#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070064#include "runtime.h"
Ian Rogers7655f292013-07-29 11:07:13 -070065#include "entrypoints/entrypoint_utils.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070066#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070067#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070068#include "handle_scope-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070069#include "thread.h"
70#include "utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080071#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070072#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070073
74namespace art {
75
Ian Rogers00f7d0e2012-07-19 15:28:27 -070076static void ThrowNoClassDefFoundError(const char* fmt, ...)
77 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070078 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070079static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070080 va_list args;
81 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -080082 Thread* self = Thread::Current();
83 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
84 self->ThrowNewExceptionV(throw_location, "Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080085 va_end(args);
86}
87
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080088static void ThrowEarlierClassFailure(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -070089 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5c599942012-06-13 16:45:05 -070090 // The class failed to initialize on a previous attempt, so we want to throw
91 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
92 // failed in verification, in which case v2 5.4.1 says we need to re-throw
93 // the previous error.
Ian Rogers87e552d2012-08-31 15:54:48 -070094 if (!Runtime::Current()->IsCompiler()) { // Give info if this occurs at runtime.
95 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
96 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -070097
Elliott Hughes5c599942012-06-13 16:45:05 -070098 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -080099 Thread* self = Thread::Current();
100 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700101 if (c->GetVerifyErrorClass() != NULL) {
102 // TODO: change the verifier to store an _instance_, with a useful detail message?
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700103 std::string temp;
104 self->ThrowNewException(throw_location, c->GetVerifyErrorClass()->GetDescriptor(&temp),
Mathieu Chartierf8322842014-05-16 10:59:25 -0700105 PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700106 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -0800107 self->ThrowNewException(throw_location, "Ljava/lang/NoClassDefFoundError;",
108 PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700109 }
110}
111
Ian Rogers62d6c772013-02-27 08:32:07 -0800112static void WrapExceptionInInitializer() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700113 Thread* self = Thread::Current();
114 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700115
116 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
117 CHECK(cause.get() != NULL);
118
119 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700120 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
121 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700122
Elliott Hughesa4f94742012-05-29 16:28:38 -0700123 // We only wrap non-Error exceptions; an Error can just be used as-is.
124 if (!is_error) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800125 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
126 self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;", NULL);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700127 }
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700128}
129
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800130static size_t Hash(const char* s) {
131 // This is the java.lang.String hashcode for convenience, not interoperability.
132 size_t hash = 0;
133 for (; *s != '\0'; ++s) {
134 hash = hash * 31 + *s;
135 }
136 return hash;
137}
138
Elliott Hughes418d20f2011-09-22 14:00:39 -0700139const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700140 "Ljava/lang/Class;",
141 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700142 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700143 "[Ljava/lang/Object;",
144 "Ljava/lang/String;",
Mathieu Chartier66f19252012-09-18 08:57:04 -0700145 "Ljava/lang/DexCache;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700146 "Ljava/lang/ref/Reference;",
Brian Carlstromea46f952013-07-30 01:26:50 -0700147 "Ljava/lang/reflect/ArtField;",
148 "Ljava/lang/reflect/ArtMethod;",
Ian Rogers466bb252011-10-14 03:29:56 -0700149 "Ljava/lang/reflect/Proxy;",
Mathieu Chartier66f19252012-09-18 08:57:04 -0700150 "[Ljava/lang/String;",
Brian Carlstromea46f952013-07-30 01:26:50 -0700151 "[Ljava/lang/reflect/ArtField;",
152 "[Ljava/lang/reflect/ArtMethod;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700153 "Ljava/lang/ClassLoader;",
Ian Rogers5167c972012-02-03 10:41:20 -0800154 "Ljava/lang/Throwable;",
jeffhao8cd6dda2012-02-22 10:15:34 -0800155 "Ljava/lang/ClassNotFoundException;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700156 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700157 "Z",
158 "B",
159 "C",
160 "D",
161 "F",
162 "I",
163 "J",
164 "S",
165 "V",
166 "[Z",
167 "[B",
168 "[C",
169 "[D",
170 "[F",
171 "[I",
172 "[J",
173 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700174 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700175};
176
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800177ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700178 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700179 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700180 dex_cache_image_class_lookup_required_(false),
181 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800182 class_roots_(nullptr),
183 array_iftable_(nullptr),
184 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700185 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800186 log_new_dex_caches_roots_(false),
187 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700188 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800189 portable_resolution_trampoline_(nullptr),
190 quick_resolution_trampoline_(nullptr),
191 portable_imt_conflict_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800192 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100193 quick_generic_jni_trampoline_(nullptr),
194 quick_to_interpreter_bridge_trampoline_(nullptr) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700195 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Ian Rogers98379392014-02-24 16:53:16 -0800196 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700197}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700198
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700199// To set a value for generic JNI. May be necessary in compiler tests.
200extern "C" void art_quick_generic_jni_trampoline(mirror::ArtMethod*);
201
Brian Carlstroma004aa92012-02-08 18:05:09 -0800202void ClassLinker::InitFromCompiler(const std::vector<const DexFile*>& boot_class_path) {
203 VLOG(startup) << "ClassLinker::Init";
204 CHECK(Runtime::Current()->IsCompiler());
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700205
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700206 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700207
Elliott Hughes30646832011-10-13 16:59:46 -0700208 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700209 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700210 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700211 // The GC can't handle an object with a null class since we can't get the size of this object.
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800212 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700213 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
214 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700215 heap->AllocNonMovableObject<true>(self, nullptr,
216 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700217 VoidFunctor()))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700218 CHECK(java_lang_Class.Get() != NULL);
219 mirror::Class::SetClassClass(java_lang_Class.Get());
220 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700221 if (kUseBakerOrBrooksReadBarrier) {
222 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800223 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700224 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800225 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800226 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700227
Elliott Hughes418d20f2011-09-22 14:00:39 -0700228 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700229 Handle<mirror::Class> class_array_class(hs.NewHandle(
230 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700231 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700232
Ian Rogers23435d02012-09-24 11:23:12 -0700233 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700234 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
235 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700236 CHECK(java_lang_Object.Get() != NULL);
Ian Rogers23435d02012-09-24 11:23:12 -0700237 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700238 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700239 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700240
Ian Rogers23435d02012-09-24 11:23:12 -0700241 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700242 Handle<mirror::Class> object_array_class(hs.NewHandle(
243 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700244 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700245
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700246 // Setup the char (primitive) class to be used for char[].
247 Handle<mirror::Class> char_class(hs.NewHandle(
248 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700249
Ian Rogers23435d02012-09-24 11:23:12 -0700250 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700251 Handle<mirror::Class> char_array_class(hs.NewHandle(
252 AllocClass(self, java_lang_Class.Get(),
253 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700254 char_array_class->SetComponentType(char_class.Get());
255 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700256
Ian Rogers23435d02012-09-24 11:23:12 -0700257 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700258 Handle<mirror::Class> java_lang_String(hs.NewHandle(
259 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700260 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700261 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700262 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400263
Fred Shih4ee7a662014-07-11 09:59:27 -0700264 // Setup Reference.
265 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
266 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
267 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
268 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
269 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
270
Ian Rogers23435d02012-09-24 11:23:12 -0700271 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700272 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
273 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
274 kClassRootsMax));
275 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700276 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
277 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
278 SetClassRoot(kClassArrayClass, class_array_class.Get());
279 SetClassRoot(kObjectArrayClass, object_array_class.Get());
280 SetClassRoot(kCharArrayClass, char_array_class.Get());
281 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700282 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700283
284 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700285 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
286 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
287 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
288 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
289 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
290 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
291 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
292 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700293
Ian Rogers23435d02012-09-24 11:23:12 -0700294 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700295 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700296
Ian Rogers23435d02012-09-24 11:23:12 -0700297 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700298 Handle<mirror::Class> int_array_class(hs.NewHandle(
299 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700300 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700301 mirror::IntArray::SetArrayClass(int_array_class.Get());
302 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700303
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700304 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700305
Ian Rogers52813c92012-10-11 11:50:38 -0700306 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700307 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
308 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700309 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700310 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700311 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700312
Brian Carlstromf3632832014-05-20 15:36:53 -0700313 // Constructor, Field, Method, and AbstractMethod are necessary so
314 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700315 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
316 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700317 CHECK(java_lang_reflect_ArtField.Get() != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700318 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700319 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700320 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700321 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700322
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700323 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
324 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700325 CHECK(java_lang_reflect_ArtMethod.Get() != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700326 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700327 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700328 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700329
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700330 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700331
332 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700333 Handle<mirror::Class> object_array_string(hs.NewHandle(
334 AllocClass(self, java_lang_Class.Get(),
335 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700336 object_array_string->SetComponentType(java_lang_String.Get());
337 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700338
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700339 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
340 AllocClass(self, java_lang_Class.Get(),
341 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700342 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
343 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700344
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700345 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
346 AllocClass(self, java_lang_Class.Get(),
347 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700348 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
349 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700350
Ian Rogers23435d02012-09-24 11:23:12 -0700351 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
352 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
353 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700354 CHECK_NE(0U, boot_class_path.size());
355 for (size_t i = 0; i != boot_class_path.size(); ++i) {
356 const DexFile* dex_file = boot_class_path[i];
357 CHECK(dex_file != NULL);
358 AppendToBootClassPath(*dex_file);
359 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700360
361 // now we can use FindSystemClass
362
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700363 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700364 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
365 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700366
Jeff Hao88474b42013-10-23 16:24:40 -0700367 // Create runtime resolution and imt conflict methods. Also setup the default imt.
368 Runtime* runtime = Runtime::Current();
369 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
370 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
371 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
372
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700373 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
374 // we do not need friend classes or a publicly exposed setter.
375 quick_generic_jni_trampoline_ = reinterpret_cast<void*>(art_quick_generic_jni_trampoline);
376
Mathieu Chartier66f19252012-09-18 08:57:04 -0700377 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700378 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800379 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700380 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700381 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700382 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800383 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700384 std::ostringstream os1, os2;
385 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
386 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
387 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
388 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700389 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800390 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700391 CHECK_EQ(java_lang_String.Get(), String_class);
392 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700393 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700394
Ian Rogers23435d02012-09-24 11:23:12 -0700395 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800396 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800397 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700398
Ian Rogers98379392014-02-24 16:53:16 -0800399 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800400 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700401
Ian Rogers98379392014-02-24 16:53:16 -0800402 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700403 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700404
Ian Rogers98379392014-02-24 16:53:16 -0800405 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800406 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700407
Ian Rogers98379392014-02-24 16:53:16 -0800408 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700409 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700410
Ian Rogers98379392014-02-24 16:53:16 -0800411 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800412 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413
Ian Rogers98379392014-02-24 16:53:16 -0800414 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800415 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700416
Ian Rogers98379392014-02-24 16:53:16 -0800417 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800418 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700419
Ian Rogers98379392014-02-24 16:53:16 -0800420 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700421 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700422
Ian Rogers98379392014-02-24 16:53:16 -0800423 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700424 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700425
Ian Rogers23435d02012-09-24 11:23:12 -0700426 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800427 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700428 CHECK(java_lang_Cloneable != NULL);
Ian Rogers98379392014-02-24 16:53:16 -0800429 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700430 CHECK(java_io_Serializable != NULL);
Ian Rogers23435d02012-09-24 11:23:12 -0700431 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
432 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700433 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700434 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700435 array_iftable->SetInterface(0, java_lang_Cloneable);
436 array_iftable->SetInterface(1, java_io_Serializable);
437 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700438
Ian Rogers23435d02012-09-24 11:23:12 -0700439 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700440 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
441 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
442 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
443 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700444 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700445 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800446 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700447 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700448
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700449 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800450 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700451 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700452
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700453 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800454 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700455 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700456
Brian Carlstromf3632832014-05-20 15:36:53 -0700457 mirror::Class* String_array_class =
458 FindSystemClass(self, class_roots_descriptors_[kJavaLangStringArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700459 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700460
Brian Carlstromea46f952013-07-30 01:26:50 -0700461 mirror::Class* Art_method_array_class =
Ian Rogers98379392014-02-24 16:53:16 -0800462 FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700463 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700464
Brian Carlstromea46f952013-07-30 01:26:50 -0700465 mirror::Class* Art_field_array_class =
Ian Rogers98379392014-02-24 16:53:16 -0800466 FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700467 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700468
Ian Rogers23435d02012-09-24 11:23:12 -0700469 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700470
Ian Rogers23435d02012-09-24 11:23:12 -0700471 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800472 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700473 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
474
Brian Carlstrom1f870082011-08-23 16:02:11 -0700475 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700476 // finish initializing Reference class
477 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
478 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
479 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
480 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
481 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700482 mirror::Class* java_lang_ref_FinalizerReference =
483 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700484 java_lang_ref_FinalizerReference->SetAccessFlags(
485 java_lang_ref_FinalizerReference->GetAccessFlags() |
486 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700487 mirror::Class* java_lang_ref_PhantomReference =
488 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700489 java_lang_ref_PhantomReference->SetAccessFlags(
490 java_lang_ref_PhantomReference->GetAccessFlags() |
491 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700492 mirror::Class* java_lang_ref_SoftReference =
493 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700494 java_lang_ref_SoftReference->SetAccessFlags(
495 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700496 mirror::Class* java_lang_ref_WeakReference =
497 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700498 java_lang_ref_WeakReference->SetAccessFlags(
499 java_lang_ref_WeakReference->GetAccessFlags() |
500 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700501
Ian Rogers23435d02012-09-24 11:23:12 -0700502 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800503 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700504 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700505 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
506
jeffhao8cd6dda2012-02-22 10:15:34 -0800507 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700508 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800509 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800510 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700511 SetClassRoot(kJavaLangClassNotFoundException,
512 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800513 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700514 SetClassRoot(kJavaLangStackTraceElementArrayClass,
515 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800516 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700517
Ian Rogers98379392014-02-24 16:53:16 -0800518 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700519
Brian Carlstroma004aa92012-02-08 18:05:09 -0800520 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700521}
522
Ian Rogers98379392014-02-24 16:53:16 -0800523void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800524 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700525
526 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700527 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700528 // as the types of the field can't be resolved prior to the runtime being
529 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800530 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700531 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800532 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800533
Brian Carlstromea46f952013-07-30 01:26:50 -0700534 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700535 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
536 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700537
Brian Carlstromea46f952013-07-30 01:26:50 -0700538 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700539 CHECK_STREQ(queue->GetName(), "queue");
540 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700541
Brian Carlstromea46f952013-07-30 01:26:50 -0700542 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700543 CHECK_STREQ(queueNext->GetName(), "queueNext");
544 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700545
Brian Carlstromea46f952013-07-30 01:26:50 -0700546 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700547 CHECK_STREQ(referent->GetName(), "referent");
548 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700549
Brian Carlstromea46f952013-07-30 01:26:50 -0700550 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700551 CHECK_STREQ(zombie->GetName(), "zombie");
552 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700553
Brian Carlstroma663ea52011-08-19 23:33:41 -0700554 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700555 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700556 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800557 mirror::Class* klass = GetClassRoot(class_root);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700558 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700559 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700560 // note SetClassRoot does additional validation.
561 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700562 }
563
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700564 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700565
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700566 // disable the slow paths in FindClass and CreatePrimitiveClass now
567 // that Object, Class, and Object[] are setup
568 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700569
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800570 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700571}
572
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700573void ClassLinker::RunRootClinits() {
574 Thread* self = Thread::Current();
575 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800576 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700577 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700578 StackHandleScope<1> hs(self);
579 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
580 EnsureInitialized(h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700581 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700582 }
583 }
584}
585
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700586bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800587 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000588 const char* oat_cache_filename,
589 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700590 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700591 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800592
Ian Rogers1d54e732013-05-02 21:10:01 -0700593 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800594 std::string boot_image_option("--boot-image=");
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700595 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800596
Brian Carlstrom6449c622014-02-10 23:48:36 -0800597 std::string dex_file_option("--dex-file=");
598 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800599
Brian Carlstrom6449c622014-02-10 23:48:36 -0800600 std::string oat_fd_option("--oat-fd=");
601 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800602
Brian Carlstrom6449c622014-02-10 23:48:36 -0800603 std::string oat_location_option("--oat-location=");
604 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800605
Brian Carlstrom6449c622014-02-10 23:48:36 -0800606 std::vector<std::string> argv;
607 argv.push_back(dex2oat);
608 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800609 argv.push_back("-classpath");
610 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800611 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800612
Ian Rogers8afeb852014-04-02 14:55:49 -0700613 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800614
Jeff Hao4a200f52014-04-01 14:58:49 -0700615 if (!Runtime::Current()->IsVerificationEnabled()) {
616 argv.push_back("--compiler-filter=verify-none");
617 }
618
Alex Light345c4b12014-07-18 14:57:04 -0700619 if (Runtime::Current()->MustRelocateIfPossible()) {
620 argv.push_back("--runtime-arg");
621 argv.push_back("-Xrelocate");
622 } else {
623 argv.push_back("--runtime-arg");
624 argv.push_back("-Xnorelocate");
625 }
626
Brian Carlstrom6449c622014-02-10 23:48:36 -0800627 if (!kIsTargetBuild) {
628 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700629 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700630
Brian Carlstrom6449c622014-02-10 23:48:36 -0800631 argv.push_back(boot_image_option);
632 argv.push_back(dex_file_option);
633 argv.push_back(oat_fd_option);
634 argv.push_back(oat_location_option);
635 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800636 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800637 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700638 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800639
640 return Exec(argv, error_msg);
jeffhao262bf462011-10-20 18:36:32 -0700641}
642
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700643const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700644 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800645 if (kIsDebugBuild) {
646 for (size_t i = 0; i < oat_files_.size(); ++i) {
647 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700648 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800649 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700650 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
651 oat_files_.push_back(oat_file);
652 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800653}
654
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700655OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
656 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700657 OatFile* oat_file = space->ReleaseOatFile();
658 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700659 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700660 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700661}
662
Brian Carlstromae826982011-11-09 01:33:42 -0800663const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800664 const char* dex_location = dex_file.GetLocation().c_str();
665 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700666 return FindOpenedOatFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800667}
668
Andreas Gampe833a4852014-05-21 18:46:59 -0700669const OatFile* ClassLinker::FindOpenedOatFile(const char* oat_location, const char* dex_location,
670 const uint32_t* const dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700671 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromae826982011-11-09 01:33:42 -0800672 for (size_t i = 0; i < oat_files_.size(); i++) {
673 const OatFile* oat_file = oat_files_[i];
674 DCHECK(oat_file != NULL);
Andreas Gampe833a4852014-05-21 18:46:59 -0700675
676 if (oat_location != nullptr) {
677 if (oat_file->GetLocation() != oat_location) {
678 continue;
679 }
680 }
681
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700682 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800683 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700684 false);
Brian Carlstroma004aa92012-02-08 18:05:09 -0800685 if (oat_dex_file != NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800686 return oat_file;
687 }
688 }
689 return NULL;
690}
691
Andreas Gampe833a4852014-05-21 18:46:59 -0700692static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file, const char* dex_location,
693 bool generated,
694 std::vector<std::string>* error_msgs,
695 std::vector<const DexFile*>* dex_files) {
696 if (oat_file == nullptr) {
697 return false;
698 }
699
700 size_t old_size = dex_files->size(); // To rollback on error.
701
702 bool success = true;
703 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100704 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700705 const char* next_name = next_name_str.c_str();
706
707 uint32_t dex_location_checksum;
708 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
709 std::string error_msg;
710 if (!DexFile::GetChecksum(next_name, dex_location_checksum_pointer, &error_msg)) {
711 DCHECK_EQ(false, i == 0 && generated);
712 dex_location_checksum_pointer = nullptr;
713 }
714
715 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
716
717 if (oat_dex_file == nullptr) {
718 if (i == 0 && generated) {
719 std::string error_msg;
720 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
721 " file'%s'", dex_location, dex_location_checksum,
722 oat_file->GetLocation().c_str());
723 error_msgs->push_back(error_msg);
724 }
725 break; // Not found, done.
726 }
727
728 // Checksum test. Test must succeed when generated.
729 success = !generated;
730 if (dex_location_checksum_pointer != nullptr) {
731 success = dex_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
732 }
733
734 if (success) {
735 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
736 if (dex_file == nullptr) {
737 success = false;
738 error_msgs->push_back(error_msg);
739 } else {
740 dex_files->push_back(dex_file);
741 }
742 }
743
744 // When we generated the file, we expect success, or something is terribly wrong.
745 CHECK_EQ(false, generated && !success)
746 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
747 << std::hex << " dex_location_checksum=" << dex_location_checksum
748 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
749 }
750
751 if (dex_files->size() == old_size) {
752 success = false; // We did not even find classes.dex
753 }
754
755 if (success) {
756 return true;
757 } else {
758 // Free all the dex files we have loaded.
759 auto it = dex_files->begin() + old_size;
760 auto it_end = dex_files->end();
761 for (; it != it_end; it++) {
762 delete *it;
763 }
764 dex_files->erase(dex_files->begin() + old_size, it_end);
765
766 return false;
767 }
768}
769
770// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
771// complicates the loading process, as we should not use an iterative loading process, because that
772// would register the oat file and dex files that come before the broken one. Instead, check all
773// multidex ahead of time.
774bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
775 std::vector<std::string>* error_msgs,
776 std::vector<const DexFile*>* dex_files) {
777 // 1) Check whether we have an open oat file.
778 // This requires a dex checksum, use the "primary" one.
779 uint32_t dex_location_checksum;
780 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
781 bool have_checksum = true;
782 std::string checksum_error_msg;
783 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
784 dex_location_checksum_pointer = nullptr;
785 have_checksum = false;
786 }
787
788 bool needs_registering = false;
789
790 std::unique_ptr<const OatFile> open_oat_file(FindOpenedOatFile(oat_location, dex_location,
791 dex_location_checksum_pointer));
792
793 // 2) If we do not have an open one, maybe there's one on disk already.
794
795 // In case the oat file is not open, we play a locking game here so
796 // that if two different processes race to load and register or generate
797 // (or worse, one tries to open a partial generated file) we will be okay.
798 // This is actually common with apps that use DexClassLoader to work
799 // around the dex method reference limit and that have a background
800 // service running in a separate process.
801 ScopedFlock scoped_flock;
802
803 if (open_oat_file.get() == nullptr) {
804 if (oat_location != nullptr) {
805 // Can only do this if we have a checksum, else error.
806 if (!have_checksum) {
807 error_msgs->push_back(checksum_error_msg);
808 return false;
809 }
810
811 std::string error_msg;
812
813 // We are loading or creating one in the future. Time to set up the file lock.
814 if (!scoped_flock.Init(oat_location, &error_msg)) {
815 error_msgs->push_back(error_msg);
816 return false;
817 }
818
Alex Lighta59dd802014-07-02 16:28:08 -0700819 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700820 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
821 oat_location, &error_msg));
822
823 if (open_oat_file.get() == nullptr) {
824 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
825 dex_location, oat_location, error_msg.c_str());
826 VLOG(class_linker) << compound_msg;
827 error_msgs->push_back(compound_msg);
828 }
829 } else {
830 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100831 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700832 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
833 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100834 kRuntimeISA, error_msgs,
835 &obsolete_file_cleanup_failed));
836 // There's no point in going forward and eventually try to regenerate the
837 // file if we couldn't remove the obsolete one. Mostly likely we will fail
838 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100839 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
840 if (obsolete_file_cleanup_failed) {
841 return false;
842 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700843 }
844 needs_registering = true;
845 }
846
847 // 3) If we have an oat file, check all contained multidex files for our dex_location.
848 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
849 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location, false, error_msgs,
850 dex_files);
851 if (success) {
852 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
853 if (needs_registering) {
854 // We opened the oat file, so we must register it.
855 RegisterOatFile(oat_file);
856 }
857 return true;
858 } else {
859 if (needs_registering) {
860 // We opened it, delete it.
861 open_oat_file.reset();
862 } else {
863 open_oat_file.release(); // Do not delete open oat files.
864 }
865 }
866
867 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
868
869 // Need a checksum, fail else.
870 if (!have_checksum) {
871 error_msgs->push_back(checksum_error_msg);
872 return false;
873 }
874
875 // Look in cache location if no oat_location is given.
876 std::string cache_location;
877 if (oat_location == nullptr) {
878 // Use the dalvik cache.
879 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
880 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
881 oat_location = cache_location.c_str();
882 }
883
884 // Definitely need to lock now.
885 if (!scoped_flock.HasFile()) {
886 std::string error_msg;
887 if (!scoped_flock.Init(oat_location, &error_msg)) {
888 error_msgs->push_back(error_msg);
889 return false;
890 }
891 }
892
893 // Create the oat file.
894 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
895 oat_location, error_msgs));
896
897 // Failed, bail.
898 if (open_oat_file.get() == nullptr) {
899 return false;
900 }
901
902 // Try to load again, but stronger checks.
903 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location, true, error_msgs,
904 dex_files);
905 if (success) {
906 RegisterOatFile(open_oat_file.release());
907 return true;
908 } else {
909 return false;
910 }
911}
912
913const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
914 uint32_t dex_location_checksum,
915 const char* oat_location,
916 std::string* error_msg) {
Ian Rogers700a4022014-05-19 16:49:03 -0700917 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, NULL,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700918 !Runtime::Current()->IsCompiler(),
919 error_msg));
920 if (oat_file.get() == nullptr) {
921 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
922 error_msg->c_str());
923 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800924 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700925 Runtime* runtime = Runtime::Current();
926 const ImageHeader& image_header = runtime->GetHeap()->GetImageSpace()->GetImageHeader();
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700927 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
928 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
929 if (expected_image_oat_checksum != actual_image_oat_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700930 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
931 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
932 actual_image_oat_checksum);
933 return nullptr;
Brian Carlstrom28db0122012-10-18 16:20:41 -0700934 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700935
Ian Rogersef7d42f2014-01-06 12:55:46 -0800936 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700937 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
938 if (expected_image_oat_offset != actual_image_oat_offset) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800939 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
940 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700941 actual_image_oat_offset);
942 return nullptr;
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700943 }
Alex Lighta59dd802014-07-02 16:28:08 -0700944 int32_t expected_patch_delta = image_header.GetPatchDelta();
945 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
946 if (expected_patch_delta != actual_patch_delta) {
947 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
948 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
949 return nullptr;
950 }
Vladimir Marko64e7ac02014-05-01 15:43:47 +0100951 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
952 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700953 if (oat_dex_file == nullptr) {
954 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
955 dex_location);
956 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800957 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700958 uint32_t expected_dex_checksum = dex_location_checksum;
959 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
960 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700961 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
962 "found 0x%x", oat_location, expected_dex_checksum,
963 actual_dex_checksum);
964 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800965 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700966 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
967 if (dex_file.get() != nullptr) {
968 return oat_file.release();
969 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700970 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700971 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700972}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700973
Andreas Gampe833a4852014-05-21 18:46:59 -0700974const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
975 int fd, const char* oat_location,
976 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800977 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700978 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -0700979 std::string error_msg;
980 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -0700981 CHECK(!error_msg.empty());
982 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700983 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800984 }
Ian Rogers700a4022014-05-19 16:49:03 -0700985 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, NULL,
Vladimir Marko64e7ac02014-05-01 15:43:47 +0100986 !Runtime::Current()->IsCompiler(),
987 &error_msg));
988 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700989 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
990 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -0700991 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700992 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800993 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700994
995 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800996}
997
Alex Light345c4b12014-07-18 14:57:04 -0700998bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
999 const InstructionSet instruction_set) {
1000 Runtime* runtime = Runtime::Current();
1001 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1002 uint32_t image_oat_checksum = 0;
1003 if (instruction_set == kRuntimeISA) {
1004 const ImageHeader& image_header = image_space->GetImageHeader();
1005 image_oat_checksum = image_header.GetOatChecksum();
1006 } else {
1007 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1008 image_space->GetImageLocation().c_str(), instruction_set));
1009 image_oat_checksum = image_header->GetOatChecksum();
1010 }
1011 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1012}
1013
1014bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1015 const InstructionSet instruction_set,
1016 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001017 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001018 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1019
1020 // If the requested instruction set is the same as the current runtime,
1021 // we can use the checksums directly. If it isn't, we'll have to read the
1022 // image header from the image for the right instruction set.
1023 uint32_t image_oat_checksum = 0;
1024 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001025 int32_t image_patch_delta = 0;
1026 if (instruction_set == Runtime::Current()->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001027 const ImageHeader& image_header = image_space->GetImageHeader();
1028 image_oat_checksum = image_header.GetOatChecksum();
1029 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001030 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001031 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001032 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001033 image_space->GetImageLocation().c_str(), instruction_set));
1034 image_oat_checksum = image_header->GetOatChecksum();
1035 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001036 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001037 }
1038 const OatHeader& oat_header = oat_file->GetOatHeader();
Alex Light345c4b12014-07-18 14:57:04 -07001039 bool ret = ((oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum)
1040 && (oat_header.GetImagePatchDelta() == image_patch_delta)
1041 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin));
1042 if (!ret) {
1043 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1044 oat_file->GetLocation().c_str(),
1045 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1046 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1047 oat_file->GetOatHeader().GetImagePatchDelta(),
1048 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1049 }
1050 return ret;
1051}
1052
1053bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1054 const char* dex_location,
1055 uint32_t dex_location_checksum,
1056 const InstructionSet instruction_set,
1057 std::string* error_msg) {
1058 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1059 return false;
1060 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001061
Brian Carlstromf3632832014-05-20 15:36:53 -07001062 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1063 &dex_location_checksum);
Brian Carlstromafe25512012-06-27 17:02:58 -07001064 if (oat_dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001065 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1066 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Brian Carlstromafe25512012-06-27 17:02:58 -07001067 std::vector<const OatFile::OatDexFile*> oat_dex_files = oat_file->GetOatDexFiles();
1068 for (size_t i = 0; i < oat_dex_files.size(); i++) {
1069 const OatFile::OatDexFile* oat_dex_file = oat_dex_files[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001070 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s'",
1071 oat_file->GetLocation().c_str(),
1072 oat_dex_file->GetDexFileLocation().c_str());
Brian Carlstromafe25512012-06-27 17:02:58 -07001073 }
1074 return false;
1075 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001076
Alex Light345c4b12014-07-18 14:57:04 -07001077 if (dex_location_checksum != oat_dex_file->GetDexFileLocationChecksum()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001078 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x) with '%s' (0x%x)",
1079 oat_file->GetLocation().c_str(),
1080 oat_dex_file->GetDexFileLocationChecksum(),
1081 dex_location, dex_location_checksum);
Alex Light345c4b12014-07-18 14:57:04 -07001082 return false;
Brian Carlstromafe25512012-06-27 17:02:58 -07001083 }
Alex Light345c4b12014-07-18 14:57:04 -07001084 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001085}
1086
Alex Lighta59dd802014-07-02 16:28:08 -07001087bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1088 const char* dex_location,
1089 std::string* error_msg) {
1090 CHECK(oat_file != nullptr);
1091 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001092 std::unique_ptr<const DexFile> dex_file;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001093 uint32_t dex_location_checksum;
1094 if (!DexFile::GetChecksum(dex_location, &dex_location_checksum, error_msg)) {
1095 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1096 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1097 // directory.
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001098 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, NULL);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001099 if (oat_dex_file == nullptr) {
1100 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001101 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001102 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001103 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001104 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001105 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001106 } else {
Alex Light345c4b12014-07-18 14:57:04 -07001107 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, dex_location_checksum,
1108 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001109 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001110 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001111 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001112 dex_file.reset(oat_file->GetOatDexFile(dex_location,
1113 &dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001114 }
Alex Lighta59dd802014-07-02 16:28:08 -07001115 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001116}
1117
Andreas Gampe833a4852014-05-21 18:46:59 -07001118const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001119 const char* dex_location,
1120 const uint32_t* const dex_location_checksum,
1121 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001122 std::vector<std::string>* error_msgs,
1123 bool* obsolete_file_cleanup_failed) {
1124 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001125 bool already_opened = false;
1126 std::string dex_location_str(dex_location);
1127 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1128 &already_opened,
1129 obsolete_file_cleanup_failed,
1130 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001131 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001132 if (oat_file.get() == nullptr) {
1133 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1134 dex_location));
1135 return nullptr;
1136 } else if (!VerifyOatWithDexFile(oat_file.get(), dex_location, &error_msg)) {
1137 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1138 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001139 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001140 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001141 } else {
1142 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001143 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001144}
1145
Brian Carlstromae826982011-11-09 01:33:42 -08001146const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001147 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001148 for (size_t i = 0; i < oat_files_.size(); i++) {
1149 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001150 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001151 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001152 return oat_file;
1153 }
1154 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001155 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001156}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001157
Alex Lighta59dd802014-07-02 16:28:08 -07001158const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1159 InstructionSet isa,
1160 bool *already_opened,
1161 bool *obsolete_file_cleanup_failed,
1162 std::vector<std::string>* error_msgs) {
1163 // Find out if we've already opened the file
1164 const OatFile* ret = nullptr;
1165 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1166 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1167 if (ret != nullptr) {
1168 *already_opened = true;
1169 return ret;
1170 }
1171
1172 std::string dalvik_cache;
1173 bool have_android_data = false;
1174 bool have_dalvik_cache = false;
1175 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
1176 &have_android_data, &have_dalvik_cache);
1177 std::string cache_filename;
1178 if (have_dalvik_cache) {
1179 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1180 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1181 if (ret != nullptr) {
1182 *already_opened = true;
1183 return ret;
1184 }
1185 } else {
1186 // If we need to relocate we should just place odex back where it started.
1187 cache_filename = odex_filename;
1188 }
1189
1190 ret = nullptr;
1191
1192 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1193 //
1194 // Now we do the following:
1195 // 1) Try and open the odex version
1196 // 2) If present, checksum-verified & relocated correctly return it
1197 // 3) Close the odex version to free up its address space.
1198 // 4) Try and open the cache version
1199 // 5) If present, checksum-verified & relocated correctly return it
1200 // 6) Close the cache version to free up its address space.
1201 // 7) If we should relocate:
1202 // a) If we have opened and checksum-verified the odex version relocate it to
1203 // 'cache_filename' and return it
1204 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1205 // it. This should not happen often (I think only the run-test's will hit this case).
1206 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1207 // this point.
1208 // 9) Return nullptr
1209
1210 *already_opened = false;
1211 const Runtime* runtime = Runtime::Current();
1212 CHECK(runtime != nullptr);
1213 bool executable = !runtime->IsCompiler();
1214
1215 std::string odex_error_msg;
1216 bool should_patch_system = false;
1217 bool odex_checksum_verified = false;
1218 {
1219 // There is a high probability that these both these oat files map similar/the same address
1220 // spaces so we must scope them like this so they each gets its turn.
1221 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, NULL,
1222 executable, &odex_error_msg));
1223 if (odex_oat_file.get() != nullptr && CheckOatFile(odex_oat_file.get(), isa,
1224 &odex_checksum_verified,
1225 &odex_error_msg)) {
1226 error_msgs->push_back(odex_error_msg);
1227 return odex_oat_file.release();
1228 } else if (odex_checksum_verified) {
1229 // We can just relocate
1230 should_patch_system = true;
1231 odex_error_msg = "Image Patches are incorrect";
1232 }
1233 }
1234
1235
1236 std::string cache_error_msg;
1237 bool should_patch_cache = false;
1238 bool cache_checksum_verified = false;
1239 if (have_dalvik_cache) {
1240 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, NULL,
1241 executable, &cache_error_msg));
1242 if (cache_oat_file.get() != nullptr && CheckOatFile(cache_oat_file.get(), isa,
1243 &cache_checksum_verified,
1244 &cache_error_msg)) {
1245 error_msgs->push_back(cache_error_msg);
1246 return cache_oat_file.release();
1247 } else if (cache_checksum_verified) {
1248 // We can just relocate
1249 should_patch_cache = true;
1250 cache_error_msg = "Image Patches are incorrect";
1251 }
1252 } else if (have_android_data) {
1253 // dalvik_cache does not exist but android data does. This means we should be able to create
1254 // it, so we should try.
1255 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1256 }
1257
1258 ret = nullptr;
1259 std::string error_msg;
1260 if (runtime->CanRelocate()) {
1261 // Run relocation
1262 const std::string& image_location =
1263 Runtime::Current()->GetHeap()->GetImageSpace()->GetImageLocation();
1264 if (odex_checksum_verified && should_patch_system) {
1265 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1266 } else if (cache_checksum_verified && should_patch_cache) {
1267 CHECK(have_dalvik_cache);
1268 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1269 }
1270 }
1271 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1272 // implicitly: were able to fine where the cached version is but we were unable to use it,
1273 // either as a destination for relocation or to open a file. We should delete it if it is
1274 // there.
1275 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1276 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1277 "searching for dex file %s: %s",
1278 cache_filename.c_str(), dex_location.c_str(),
1279 strerror(errno));
1280 error_msgs->push_back(rm_error_msg);
1281 VLOG(class_linker) << rm_error_msg;
1282 // Let the caller know that we couldn't remove the obsolete file.
1283 // This is a good indication that further writes may fail as well.
1284 *obsolete_file_cleanup_failed = true;
1285 }
1286 }
1287 if (ret == nullptr) {
1288 VLOG(class_linker) << error_msg;
1289 error_msgs->push_back(error_msg);
1290 std::string relocation_msg;
1291 if (runtime->CanRelocate()) {
1292 relocation_msg = StringPrintf(" and relocation failed");
1293 }
1294 if (have_dalvik_cache && cache_checksum_verified) {
1295 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1296 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1297 cache_filename.c_str(), cache_error_msg.c_str(),
1298 relocation_msg.c_str());
1299 } else {
1300 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1301 "dalvik_cache availible)%s.", odex_filename.c_str(),
1302 odex_error_msg.c_str(), relocation_msg.c_str());
1303 }
1304 VLOG(class_linker) << error_msg;
1305 error_msgs->push_back(error_msg);
1306 }
1307 return ret;
1308}
1309
1310const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1311 const std::string& output_oat,
1312 const std::string& image_location,
1313 InstructionSet isa,
1314 std::string* error_msg) {
1315 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
1316 std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
1317
1318 std::string isa_arg("--instruction-set=");
1319 isa_arg += GetInstructionSetString(isa);
1320 std::string input_oat_filename_arg("--input-oat-file=");
1321 input_oat_filename_arg += input_oat;
1322 std::string output_oat_filename_arg("--output-oat-file=");
1323 output_oat_filename_arg += output_oat;
1324 std::string patched_image_arg("--patched-image-location=");
1325 patched_image_arg += image_location;
1326
1327 std::vector<std::string> argv;
1328 argv.push_back(patchoat);
1329 argv.push_back(isa_arg);
1330 argv.push_back(input_oat_filename_arg);
1331 argv.push_back(output_oat_filename_arg);
1332 argv.push_back(patched_image_arg);
1333
1334 std::string command_line(Join(argv, ' '));
1335 LOG(INFO) << "Relocate Oat File: " << command_line;
1336 bool success = Exec(argv, error_msg);
1337 if (success) {
1338 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, NULL,
1339 !Runtime::Current()->IsCompiler(), error_msg));
1340 bool checksum_verified = false;
1341 if (output.get() != nullptr && CheckOatFile(output.get(), isa, &checksum_verified, error_msg)) {
1342 return output.release();
1343 } else if (output.get() != nullptr) {
1344 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1345 "but output file '%s' failed verifcation: %s",
1346 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1347 } else {
1348 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1349 "but was unable to open output file '%s': %s",
1350 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1351 }
1352 } else {
1353 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1354 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1355 error_msg->c_str());
1356 }
1357 return nullptr;
1358}
1359
1360int32_t ClassLinker::GetRequiredDelta(const OatFile* oat_file, InstructionSet isa) {
1361 Runtime* runtime = Runtime::Current();
1362 int32_t real_patch_delta;
1363 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1364 if (isa == Runtime::Current()->GetInstructionSet()) {
1365 const ImageHeader& image_header = image_space->GetImageHeader();
1366 real_patch_delta = image_header.GetPatchDelta();
1367 } else {
1368 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1369 image_space->GetImageLocation().c_str(), isa));
1370 real_patch_delta = image_header->GetPatchDelta();
1371 }
1372 const OatHeader& oat_header = oat_file->GetOatHeader();
1373 return real_patch_delta - oat_header.GetImagePatchDelta();
1374}
1375
1376bool ClassLinker::CheckOatFile(const OatFile* oat_file, InstructionSet isa,
1377 bool* checksum_verified,
1378 std::string* error_msg) {
1379 std::string compound_msg("Oat file failed to verify: ");
1380 Runtime* runtime = Runtime::Current();
1381 uint32_t real_image_checksum;
1382 void* real_image_oat_offset;
1383 int32_t real_patch_delta;
1384 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1385 if (isa == Runtime::Current()->GetInstructionSet()) {
1386 const ImageHeader& image_header = image_space->GetImageHeader();
1387 real_image_checksum = image_header.GetOatChecksum();
1388 real_image_oat_offset = image_header.GetOatDataBegin();
1389 real_patch_delta = image_header.GetPatchDelta();
1390 } else {
1391 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1392 image_space->GetImageLocation().c_str(), isa));
1393 real_image_checksum = image_header->GetOatChecksum();
1394 real_image_oat_offset = image_header->GetOatDataBegin();
1395 real_patch_delta = image_header->GetPatchDelta();
1396 }
1397
1398 const OatHeader& oat_header = oat_file->GetOatHeader();
1399
1400 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1401 *checksum_verified = oat_image_checksum == real_image_checksum;
1402 if (!*checksum_verified) {
1403 compound_msg += StringPrintf(" Oat Image Checksum Incorrect (expected 0x%x, recieved 0x%x)",
1404 real_image_checksum, oat_image_checksum);
1405 }
1406
1407 void* oat_image_oat_offset =
1408 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1409 bool offset_verified = oat_image_oat_offset == real_image_oat_offset;
1410 if (!offset_verified) {
1411 compound_msg += StringPrintf(" Oat Image oat offset incorrect (expected 0x%p, recieved 0x%p)",
1412 real_image_oat_offset, oat_image_oat_offset);
1413 }
1414
1415 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1416 bool patch_delta_verified = oat_patch_delta == real_patch_delta;
1417 if (!patch_delta_verified) {
1418 compound_msg += StringPrintf(" Oat image patch delta incorrect (expected 0x%x, recieved 0x%x)",
1419 real_patch_delta, oat_patch_delta);
1420 }
1421
1422 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
1423 if (ret) {
1424 *error_msg = compound_msg;
1425 }
1426 return ret;
1427}
1428
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001429const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1430 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001431 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001432 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001433 return oat_file;
1434 }
1435
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001436 oat_file = OatFile::Open(oat_location, oat_location, NULL, !Runtime::Current()->IsCompiler(),
1437 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001438 if (oat_file == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -08001439 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001440 }
1441 return oat_file;
1442}
1443
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001444static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
Ian Rogers848871b2013-08-05 10:56:33 -07001445 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001446 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1447
Ian Rogers848871b2013-08-05 10:56:33 -07001448 DCHECK(obj != NULL);
1449 DCHECK(class_linker != NULL);
1450
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001451 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001452 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001453 if (!method->IsNative()) {
1454 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
1455 if (method != Runtime::Current()->GetResolutionMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001456 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1457 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers848871b2013-08-05 10:56:33 -07001458 }
1459 }
1460 }
1461}
1462
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001463void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001464 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001465 CHECK(!init_done_);
1466
Mathieu Chartier590fee92013-09-13 13:46:47 -07001467 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001468 gc::Heap* heap = Runtime::Current()->GetHeap();
1469 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001470 dex_cache_image_class_lookup_required_ = true;
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001471 CHECK(space != NULL);
1472 OatFile& oat_file = GetImageOatFile(space);
1473 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1474 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001475 const char* image_file_location = oat_file.GetOatHeader().
1476 GetStoreValueByKey(OatHeader::kImageLocationKey);
1477 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001478 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1479 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001480 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1481 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001482 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001483 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001484 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1485 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1486 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001487
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001488 StackHandleScope<1> hs(self);
1489 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1490 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1491 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001492 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001493
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001494 // Special case of setting up the String class early so that we can test arbitrary objects
1495 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001496 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001497
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001498 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001499 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001500 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001501 StackHandleScope<1> hs(self);
1502 Handle<mirror::DexCache> dex_cache(hs.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001503 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001504 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1505 nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001506 CHECK(oat_dex_file != NULL) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001507 std::string error_msg;
1508 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001509 if (dex_file == NULL) {
1510 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001511 << " from within oat file " << oat_file.GetLocation()
1512 << " error '" << error_msg << "'";
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001513 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001514
1515 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1516
1517 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001518 }
1519
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001520 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1521 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001522 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001523
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001524 // Set entry point to interpreter if in InterpretOnly mode.
1525 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001526 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001527 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001528 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001529
1530 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001531 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001532 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001533
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001534 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001535 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
1536 DCHECK(array_iftable_.Read() == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001537 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001538 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001539 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001540 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1541 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1542 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1543 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1544 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1545 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1546 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1547 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1548 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1549 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001550
Ian Rogers98379392014-02-24 16:53:16 -08001551 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001552
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001553 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001554}
1555
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001556void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1557 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1558 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001559 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1560 it.second.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001561 }
1562 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1563 for (auto& pair : new_class_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001564 mirror::Class* old_ref = pair.second.Read<kWithoutReadBarrier>();
1565 pair.second.VisitRoot(callback, arg, 0, kRootStickyClass);
1566 mirror::Class* new_ref = pair.second.Read<kWithoutReadBarrier>();
1567 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001568 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1569 // corresponding object. This is slow, but luckily for us, this may only happen with a
1570 // concurrent moving GC.
1571 for (auto it = class_table_.lower_bound(pair.first), end = class_table_.end();
1572 it != end && it->first == pair.first; ++it) {
1573 // If the class stored matches the old class, update it to the new value.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001574 if (old_ref == it->second.Read<kWithoutReadBarrier>()) {
1575 it->second = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001576 }
1577 }
1578 }
1579 }
1580 }
1581 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1582 new_class_roots_.clear();
1583 }
1584 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1585 log_new_class_table_roots_ = true;
1586 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1587 log_new_class_table_roots_ = false;
1588 }
1589 // We deliberately ignore the class roots in the image since we
1590 // handle image roots by using the MS/CMS rescanning of dirty cards.
1591}
1592
Brian Carlstroma663ea52011-08-19 23:33:41 -07001593// Keep in sync with InitCallback. Anything we visit, we need to
1594// reinit references to when reinitializing a ClassLinker from a
1595// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001596void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001597 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001598 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001599 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001600 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001601 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001602 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1603 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001604 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001605 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1606 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001607 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001608 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001609 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001610 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1611 new_dex_cache_roots_.clear();
1612 }
1613 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1614 log_new_dex_caches_roots_ = true;
1615 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1616 log_new_dex_caches_roots_ = false;
1617 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001618 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001619 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001620 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1621 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001622 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001623 if (!find_array_class_cache_[i].IsNull()) {
1624 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001625 }
1626 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001627}
1628
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001629void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1630 if (dex_cache_image_class_lookup_required_) {
1631 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001632 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001633 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001634 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1635 mirror::Class* c = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07001636 if (!visitor(c, arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001637 return;
1638 }
1639 }
1640}
1641
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001642static bool GetClassesVisitor(mirror::Class* c, void* arg) {
1643 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001644 classes->insert(c);
1645 return true;
1646}
1647
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001648void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001649 std::set<mirror::Class*> classes;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001650 VisitClasses(GetClassesVisitor, &classes);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001651 for (mirror::Class* klass : classes) {
1652 if (!visitor(klass, arg)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001653 return;
1654 }
1655 }
1656}
1657
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001658ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001659 mirror::Class::ResetClass();
1660 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001661 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001662 mirror::ArtField::ResetClass();
1663 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001664 mirror::BooleanArray::ResetArrayClass();
1665 mirror::ByteArray::ResetArrayClass();
1666 mirror::CharArray::ResetArrayClass();
1667 mirror::DoubleArray::ResetArrayClass();
1668 mirror::FloatArray::ResetArrayClass();
1669 mirror::IntArray::ResetArrayClass();
1670 mirror::LongArray::ResetArrayClass();
1671 mirror::ShortArray::ResetArrayClass();
1672 mirror::Throwable::ResetClass();
1673 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001674 STLDeleteElements(&boot_class_path_);
1675 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001676}
1677
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001678mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001679 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001680 StackHandleScope<16> hs(self);
1681 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1682 Handle<mirror::DexCache> dex_cache(
1683 hs.NewHandle(down_cast<mirror::DexCache*>(
1684 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1685 VoidFunctor()))));
1686 if (dex_cache.Get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001687 return NULL;
1688 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001689 Handle<mirror::String>
1690 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
1691 if (location.Get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001692 return NULL;
1693 }
Ian Rogers700a4022014-05-19 16:49:03 -07001694 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001695 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
1696 if (strings.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001697 return NULL;
1698 }
Ian Rogers700a4022014-05-19 16:49:03 -07001699 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001700 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
1701 if (types.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001702 return NULL;
1703 }
Ian Rogers700a4022014-05-19 16:49:03 -07001704 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001705 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
1706 if (methods.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001707 return NULL;
1708 }
Ian Rogers700a4022014-05-19 16:49:03 -07001709 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001710 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
1711 if (fields.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001712 return NULL;
1713 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001714 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1715 fields.Get());
1716 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001717}
1718
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001719mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001720 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001721 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001722 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001723 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001724 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001725 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1726 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001727 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001728 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001729 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001730 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001731 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001732}
1733
Ian Rogers6fac4472014-02-25 17:01:10 -08001734mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001735 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001736}
1737
Brian Carlstromea46f952013-07-30 01:26:50 -07001738mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001739 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001740 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001741}
1742
Brian Carlstromea46f952013-07-30 01:26:50 -07001743mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001744 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001745 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001746}
1747
Mathieu Chartier590fee92013-09-13 13:46:47 -07001748mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1749 Thread* self, size_t length) {
1750 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1751 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001752}
1753
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001754mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1755 mirror::Class* klass) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001756 DCHECK(klass != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001757
1758 // For temporary classes we must wait for them to be retired.
1759 if (init_done_ && klass->IsTemp()) {
1760 CHECK(!klass->IsResolved());
1761 if (klass->IsErroneous()) {
1762 ThrowEarlierClassFailure(klass);
1763 return nullptr;
1764 }
1765 StackHandleScope<1> hs(self);
1766 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1767 ObjectLock<mirror::Class> lock(self, h_class);
1768 // Loop and wait for the resolving thread to retire this class.
1769 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1770 lock.WaitIgnoringInterrupts();
1771 }
1772 if (h_class->IsErroneous()) {
1773 ThrowEarlierClassFailure(h_class.Get());
1774 return nullptr;
1775 }
1776 CHECK(h_class->IsRetired());
1777 // Get the updated class from class table.
1778 klass = LookupClass(descriptor, h_class.Get()->GetClassLoader());
1779 }
1780
Brian Carlstromaded5f72011-10-07 17:15:04 -07001781 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001782 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001783 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001784 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
1785 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001786 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001787 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
1788 ThrowClassCircularityError(h_class.Get());
1789 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001790 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001791 }
1792 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001793 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08001794 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001795 }
1796 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001797
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001798 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001799 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001800 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001801 }
1802 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001803 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08001804 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001805 return klass;
1806}
1807
Ian Rogers98379392014-02-24 16:53:16 -08001808mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07001809 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001810 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08001811 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001812 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001813 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001814 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1815 // for primitive classes that aren't backed by dex files.
1816 return FindPrimitiveClass(descriptor[0]);
1817 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001818 // Find the class in the loaded classes table.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001819 mirror::Class* klass = LookupClass(descriptor, class_loader.Get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001820 if (klass != NULL) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001821 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001822 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001823 // Class is not yet loaded.
1824 if (descriptor[0] == '[') {
Ian Rogers98379392014-02-24 16:53:16 -08001825 return CreateArrayClass(self, descriptor, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001826 } else if (class_loader.Get() == nullptr) {
Jesse Wilson47daf872011-11-23 11:42:45 -05001827 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1828 if (pair.second != NULL) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001829 StackHandleScope<1> hs(self);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07001830 return DefineClass(descriptor, NullHandle<mirror::ClassLoader>(), *pair.first, *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05001831 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001832 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogersbe7149f2013-08-20 09:29:39 -07001833 // First try the boot class path, we check the descriptor first to avoid an unnecessary
1834 // throw of a NoClassDefFoundError.
1835 if (IsInBootClassPath(descriptor)) {
Ian Rogers98379392014-02-24 16:53:16 -08001836 mirror::Class* system_class = FindSystemClass(self, descriptor);
Ian Rogersbe7149f2013-08-20 09:29:39 -07001837 CHECK(system_class != NULL);
Jesse Wilson47daf872011-11-23 11:42:45 -05001838 return system_class;
1839 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07001840 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001841 const std::vector<const DexFile*>* class_path;
1842 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07001843 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001844 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001845 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001846 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
1847 }
1848
1849 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, *class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001850 if (pair.second != NULL) {
1851 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001852 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001853
1854 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001855 ScopedObjectAccessUnchecked soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001856 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001857 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08001858 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001859 ScopedLocalRef<jobject> result(soa.Env(), NULL);
Ian Rogers365c1022012-06-22 15:05:28 -07001860 {
1861 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001862 ScopedLocalRef<jobject> class_name_object(soa.Env(),
1863 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers365c1022012-06-22 15:05:28 -07001864 if (class_name_object.get() == NULL) {
1865 return NULL;
1866 }
1867 CHECK(class_loader_object.get() != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001868 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
1869 WellKnownClasses::java_lang_ClassLoader_loadClass,
1870 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05001871 }
Ian Rogers98379392014-02-24 16:53:16 -08001872 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001873 // If the ClassLoader threw, pass that exception up.
1874 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001875 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001876 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers62d6c772013-02-27 08:32:07 -08001877 ThrowNullPointerException(NULL, StringPrintf("ClassLoader.loadClass returned null for %s",
1878 class_name_string.c_str()).c_str());
Ian Rogerscab01012012-01-10 17:35:46 -08001879 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001880 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001881 // success, return mirror::Class*
1882 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001883 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001884 }
1885
Elliott Hughes82914b62012-04-09 15:56:29 -07001886 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001887 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001888}
1889
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001890mirror::Class* ClassLinker::DefineClass(const char* descriptor,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07001891 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001892 const DexFile& dex_file,
1893 const DexFile::ClassDef& dex_class_def) {
Ian Rogers1f539342012-10-03 21:09:42 -07001894 Thread* self = Thread::Current();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001895 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001896 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001897 bool should_allocate = false;
1898
Brian Carlstromaded5f72011-10-07 17:15:04 -07001899 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001900 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001901 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001902 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001903 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001904 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001905 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001906 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001907 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07001908 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
1909 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001910 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001911 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001912 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001913 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001914 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001915 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001916 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001917 should_allocate = true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001918 }
1919 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001920 should_allocate = true;
1921 }
1922
1923 if (should_allocate) {
1924 // Allocate a class with the status of not ready.
1925 // Interface object should get the right size here. Regular class will
1926 // figure out the right size later and be replaced with one of the right
1927 // size when the class becomes resolved.
1928 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001929 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001930 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001931 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07001932 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001933 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001934 klass->SetDexCache(FindDexCache(dex_file));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001935 LoadClass(dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001936 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07001937 if (self->IsExceptionPending()) {
1938 // An exception occured during load, set status to erroneous while holding klass' lock in case
1939 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001940 if (!klass->IsErroneous()) {
1941 klass->SetStatus(mirror::Class::kStatusError, self);
1942 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001943 return nullptr;
1944 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001945 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001946
Mathieu Chartier590fee92013-09-13 13:46:47 -07001947 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001948 mirror::Class* existing = InsertClass(descriptor, klass.Get(), Hash(descriptor));
Ian Rogersc114b5f2014-07-21 08:55:01 -07001949 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001950 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
1951 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001952 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001953 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001954
Brian Carlstromaded5f72011-10-07 17:15:04 -07001955 // Finish loading (if necessary) by finding parents
1956 CHECK(!klass->IsLoaded());
1957 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1958 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001959 if (!klass->IsErroneous()) {
1960 klass->SetStatus(mirror::Class::kStatusError, self);
1961 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001962 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001963 }
1964 CHECK(klass->IsLoaded());
1965 // Link the class (if necessary)
1966 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001967 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001968 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001969
1970 mirror::Class* new_class = nullptr;
1971 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001972 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001973 if (!klass->IsErroneous()) {
1974 klass->SetStatus(mirror::Class::kStatusError, self);
1975 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001976 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001977 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001978 CHECK(new_class != nullptr) << descriptor;
1979 CHECK(new_class->IsResolved()) << descriptor;
1980
1981 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001982
1983 /*
1984 * We send CLASS_PREPARE events to the debugger from here. The
1985 * definition of "preparation" is creating the static fields for a
1986 * class and initializing them to the standard default values, but not
1987 * executing any code (that comes later, during "initialization").
1988 *
1989 * We did the static preparation in LinkClass.
1990 *
1991 * The class has been prepared and resolved but possibly not yet verified
1992 * at this point.
1993 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001994 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001995
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001996 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001997}
1998
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001999uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2000 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002001 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002002 size_t num_ref = 0;
2003 size_t num_32 = 0;
2004 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002005 if (class_data != NULL) {
2006 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2007 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002008 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002009 char c = descriptor[0];
2010 if (c == 'L' || c == '[') {
2011 num_ref++;
2012 } else if (c == 'J' || c == 'D') {
2013 num_64++;
2014 } else {
2015 num_32++;
2016 }
2017 }
2018 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002019 return mirror::Class::ComputeClassSize(false, 0, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002020}
2021
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002022OatFile::OatClass ClassLinker::GetOatClass(const DexFile& dex_file, uint16_t class_def_idx) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002023 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Ian Rogers19846512012-02-24 11:42:47 -08002024 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002025 CHECK(oat_file != NULL) << dex_file.GetLocation();
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07002026 uint dex_location_checksum = dex_file.GetLocationChecksum();
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002027 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation().c_str(),
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07002028 &dex_location_checksum);
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002029 CHECK(oat_dex_file != NULL) << dex_file.GetLocation();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002030 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002031}
2032
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002033static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2034 uint32_t method_idx) {
2035 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
2036 const byte* class_data = dex_file.GetClassData(class_def);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002037 CHECK(class_data != NULL);
2038 ClassDataItemIterator it(dex_file, class_data);
2039 // Skip fields
2040 while (it.HasNextStaticField()) {
2041 it.Next();
2042 }
2043 while (it.HasNextInstanceField()) {
2044 it.Next();
2045 }
2046 // Process methods
2047 size_t class_def_method_index = 0;
2048 while (it.HasNextDirectMethod()) {
2049 if (it.GetMemberIndex() == method_idx) {
2050 return class_def_method_index;
2051 }
2052 class_def_method_index++;
2053 it.Next();
2054 }
2055 while (it.HasNextVirtualMethod()) {
2056 if (it.GetMemberIndex() == method_idx) {
2057 return class_def_method_index;
2058 }
2059 class_def_method_index++;
2060 it.Next();
2061 }
2062 DCHECK(!it.HasNext());
2063 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2064 return 0;
2065}
2066
Ian Rogersef7d42f2014-01-06 12:55:46 -08002067const OatFile::OatMethod ClassLinker::GetOatMethodFor(mirror::ArtMethod* method) {
Ian Rogers19846512012-02-24 11:42:47 -08002068 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002069 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002070 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002071 size_t oat_method_index;
2072 if (method->IsStatic() || method->IsDirect()) {
2073 // Simple case where the oat method index was stashed at load time.
2074 oat_method_index = method->GetMethodIndex();
2075 } else {
2076 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2077 // by search for its position in the declared virtual methods.
2078 oat_method_index = declaring_class->NumDirectMethods();
2079 size_t end = declaring_class->NumVirtualMethods();
2080 bool found = false;
2081 for (size_t i = 0; i < end; i++) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08002082 if (declaring_class->GetVirtualMethod(i) == method) {
2083 found = true;
2084 break;
2085 }
Ian Rogersf320b632012-03-13 18:47:47 -07002086 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002087 }
2088 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method);
2089 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002090 DCHECK_EQ(oat_method_index,
2091 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002092 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002093 method->GetDexMethodIndex()));
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002094 const OatFile::OatClass oat_class = GetOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2095 declaring_class->GetDexClassDefIndex());
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002096
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002097 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002098}
2099
2100// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002101const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002102 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002103 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002104 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002105 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002106 const void* result = GetOatMethodFor(method).GetQuickCode();
2107 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002108 if (method->IsNative()) {
2109 // No code and native? Use generic trampoline.
2110 result = GetQuickGenericJniTrampoline();
2111 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002112 // No code? Do we expect portable code?
2113 result = GetQuickToPortableBridge();
2114 } else {
2115 // No code? You must mean to go into the interpreter.
2116 result = GetQuickToInterpreterBridge();
2117 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002118 }
2119 return result;
TDYa12785321912012-04-01 15:24:56 -07002120}
2121
Ian Rogersef7d42f2014-01-06 12:55:46 -08002122const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2123 bool* have_portable_code) {
2124 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2125 *have_portable_code = false;
2126 if (method->IsProxyMethod()) {
2127 return GetPortableProxyInvokeHandler();
2128 }
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002129 const OatFile::OatMethod oat_method = GetOatMethodFor(method);
2130 const void* result = oat_method.GetPortableCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002131 if (result == nullptr) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002132 if (oat_method.GetQuickCode() == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002133 // No code? You must mean to go into the interpreter.
2134 result = GetPortableToInterpreterBridge();
2135 } else {
2136 // No code? But there's quick code, so use a bridge.
2137 result = GetPortableToQuickBridge();
2138 }
2139 } else {
2140 *have_portable_code = true;
2141 }
2142 return result;
2143}
2144
2145const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2146 uint32_t method_idx) {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002147 const OatFile::OatClass oat_class = GetOatClass(dex_file, class_def_idx);
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002148 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002149 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002150}
2151
2152const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2153 uint32_t method_idx) {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002154 const OatFile::OatClass oat_class = GetOatClass(dex_file, class_def_idx);
Ian Rogersef7d42f2014-01-06 12:55:46 -08002155 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002156 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002157}
2158
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002159// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002160static bool NeedsInterpreter(
2161 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2162 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002163 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002164 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002165 // May return true for native code, in the case of generic JNI
2166 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002167 return true;
2168 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002169#ifdef ART_SEA_IR_MODE
2170 ScopedObjectAccess soa(Thread::Current());
2171 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2172 LOG(INFO) << "Found " << PrettyMethod(method);
2173 return false;
2174 }
2175#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002176 // If interpreter mode is enabled, every method (except native and proxy) must
2177 // be run with interpreter.
2178 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2179 !method->IsNative() && !method->IsProxyMethod();
2180}
2181
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002182void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002183 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002184 if (klass->NumDirectMethods() == 0) {
2185 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002186 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002187 Runtime* runtime = Runtime::Current();
2188 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Ian Rogers1c829822013-09-30 18:18:50 -07002189 return; // OAT file unavailable.
Ian Rogers19846512012-02-24 11:42:47 -08002190 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07002191 const DexFile& dex_file = klass->GetDexFile();
2192 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002193 CHECK(dex_class_def != nullptr);
2194 const byte* class_data = dex_file.GetClassData(*dex_class_def);
2195 // There should always be class data if there were direct methods.
2196 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002197 const OatFile::OatClass oat_class = GetOatClass(dex_file, klass->GetDexClassDefIndex());
Ian Rogers19846512012-02-24 11:42:47 -08002198 ClassDataItemIterator it(dex_file, class_data);
2199 // Skip fields
2200 while (it.HasNextStaticField()) {
2201 it.Next();
2202 }
2203 while (it.HasNextInstanceField()) {
2204 it.Next();
2205 }
Ian Rogers1c829822013-09-30 18:18:50 -07002206 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002207 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002208 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002209 if (!method->IsStatic()) {
2210 // Only update static methods.
2211 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002212 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002213 const void* portable_code = oat_class.GetOatMethod(method_index).GetPortableCode();
2214 const void* quick_code = oat_class.GetOatMethod(method_index).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002215 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2216 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002217 if (enter_interpreter) {
2218 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002219 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002220 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
2221 quick_code = GetQuickGenericJniTrampoline();
Ian Rogers1a570662014-03-12 01:02:21 -07002222 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002223 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002224 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002225 quick_code = GetQuickToInterpreterBridge();
2226 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002227 } else {
2228 if (portable_code == nullptr) {
2229 portable_code = GetPortableToQuickBridge();
2230 } else {
2231 have_portable_code = true;
2232 }
2233 if (quick_code == nullptr) {
2234 quick_code = GetQuickToPortableBridge();
2235 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002236 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002237 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2238 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002239 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002240 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002241}
2242
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002243void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method, const OatFile::OatClass* oat_class,
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002244 const DexFile& dex_file, uint32_t dex_method_index,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002245 uint32_t method_index) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002246 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002247 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2248 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002249 // Every kind of method should at least get an invoke stub from the oat_method.
2250 // non-abstract methods also get their code pointers.
2251 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002252 oat_method.LinkMethod(method.Get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002253
Jeff Hao16743632013-05-08 10:59:04 -07002254 // Install entry point from interpreter.
Jeff Hao790ad902013-05-22 15:02:08 -07002255 Runtime* runtime = Runtime::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002256 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002257 method->GetEntryPointFromQuickCompiledCode(),
2258 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002259 if (enter_interpreter && !method->IsNative()) {
Ian Rogers848871b2013-08-05 10:56:33 -07002260 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002261 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002262 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002263 }
2264
Brian Carlstrom92827a52011-10-10 15:50:01 -07002265 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002266 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2267 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002268 return;
2269 }
Ian Rogers19846512012-02-24 11:42:47 -08002270
Ian Rogersef7d42f2014-01-06 12:55:46 -08002271 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002272 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002273 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002274 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2275 // after initializing class (see ClassLinker::InitializeClass method).
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002276 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionTrampoline());
2277 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionTrampoline());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002278 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002279 if (!method->IsNative()) {
2280 // Set entry point from compiled code if there's no code or in interpreter only mode.
2281 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2282 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2283 } else {
2284 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniTrampoline());
2285 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2286 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002287 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2288 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2289 have_portable_code = true;
2290 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2291 } else {
2292 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2293 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002294 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002295
Ian Rogers62d6c772013-02-27 08:32:07 -08002296 if (method->IsNative()) {
2297 // Unregistering restores the dlsym lookup stub.
2298 method->UnregisterNative(Thread::Current());
Andreas Gampe90546832014-03-12 18:07:19 -07002299
2300 if (enter_interpreter) {
2301 // We have a native method here without code. Then it should have either the GenericJni
2302 // trampoline as entrypoint (non-static), or the Resolution trampoline (static).
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002303 DCHECK(method->GetEntryPointFromQuickCompiledCode() == GetQuickResolutionTrampoline()
Andreas Gampe9a6a99a2014-03-14 07:52:20 -07002304 || method->GetEntryPointFromQuickCompiledCode() == GetQuickGenericJniTrampoline());
Andreas Gampe90546832014-03-12 18:07:19 -07002305 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002306 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002307
Ian Rogers62d6c772013-02-27 08:32:07 -08002308 // Allow instrumentation its chance to hijack code.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002309 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002310 method->GetEntryPointFromQuickCompiledCode(),
2311 method->GetEntryPointFromPortableCompiledCode(),
2312 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002313}
2314
Brian Carlstromf615a612011-07-23 12:50:34 -07002315void ClassLinker::LoadClass(const DexFile& dex_file,
2316 const DexFile::ClassDef& dex_class_def,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002317 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002318 mirror::ClassLoader* class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002319 CHECK(klass.Get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002320 CHECK(klass->GetDexCache() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002321 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002322 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002323 CHECK(descriptor != NULL);
2324
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002325 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002326 if (kUseBakerOrBrooksReadBarrier) {
2327 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002328 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002329 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07002330 // Make sure that none of our runtime-only flags are set.
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002331 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002332 klass->SetAccessFlags(access_flags);
2333 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002334 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002335 klass->SetStatus(mirror::Class::kStatusIdx, NULL);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002336
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002337 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002338 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002339
Ian Rogers0571d352011-11-03 19:51:38 -07002340 const byte* class_data = dex_file.GetClassData(dex_class_def);
2341 if (class_data == NULL) {
2342 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002343 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002344
2345 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2346 const OatFile::OatClass oat_class = GetOatClass(dex_file, klass->GetDexClassDefIndex());
2347 LoadClassMembers(dex_file, class_data, klass, class_loader, &oat_class);
2348 } else {
2349 LoadClassMembers(dex_file, class_data, klass, class_loader, nullptr);
2350 }
2351}
2352
2353void ClassLinker::LoadClassMembers(const DexFile& dex_file,
2354 const byte* class_data,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002355 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002356 mirror::ClassLoader* class_loader,
2357 const OatFile::OatClass* oat_class) {
2358 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002359 ClassDataItemIterator it(dex_file, class_data);
Ian Rogers50b35e22012-10-04 10:09:15 -07002360 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07002361 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002362 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
2363 if (UNLIKELY(statics == NULL)) {
2364 CHECK(self->IsExceptionPending()); // OOME.
2365 return;
2366 }
2367 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002368 }
2369 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002370 mirror::ObjectArray<mirror::ArtField>* fields =
2371 AllocArtFieldArray(self, it.NumInstanceFields());
2372 if (UNLIKELY(fields == NULL)) {
2373 CHECK(self->IsExceptionPending()); // OOME.
2374 return;
2375 }
2376 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002377 }
2378 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002379 StackHandleScope<1> hs(self);
2380 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
2381 if (UNLIKELY(sfield.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002382 CHECK(self->IsExceptionPending()); // OOME.
2383 return;
2384 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002385 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002386 LoadField(dex_file, it, klass, sfield);
2387 }
2388 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002389 StackHandleScope<1> hs(self);
2390 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
2391 if (UNLIKELY(ifield.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002392 CHECK(self->IsExceptionPending()); // OOME.
2393 return;
2394 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002395 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002396 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002397 }
2398
Ian Rogers0571d352011-11-03 19:51:38 -07002399 // Load methods.
2400 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002401 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002402 mirror::ObjectArray<mirror::ArtMethod>* directs =
2403 AllocArtMethodArray(self, it.NumDirectMethods());
2404 if (UNLIKELY(directs == NULL)) {
2405 CHECK(self->IsExceptionPending()); // OOME.
2406 return;
2407 }
2408 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002409 }
Ian Rogers0571d352011-11-03 19:51:38 -07002410 if (it.NumVirtualMethods() != 0) {
2411 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002412 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2413 AllocArtMethodArray(self, it.NumVirtualMethods());
2414 if (UNLIKELY(virtuals == NULL)) {
2415 CHECK(self->IsExceptionPending()); // OOME.
2416 return;
2417 }
2418 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002419 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002420 size_t class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002421 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002422 StackHandleScope<1> hs(self);
2423 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
2424 if (UNLIKELY(method.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002425 CHECK(self->IsExceptionPending()); // OOME.
2426 return;
2427 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002428 klass->SetDirectMethod(i, method.Get());
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002429 if (oat_class != nullptr) {
2430 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Ian Rogers0571d352011-11-03 19:51:38 -07002431 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002432 method->SetMethodIndex(class_def_method_index);
2433 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002434 }
2435 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002436 StackHandleScope<1> hs(self);
2437 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
2438 if (UNLIKELY(method.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002439 CHECK(self->IsExceptionPending()); // OOME.
2440 return;
2441 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002442 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002443 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002444 if (oat_class != nullptr) {
2445 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Ian Rogers0571d352011-11-03 19:51:38 -07002446 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002447 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002448 }
2449 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002450}
2451
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002452void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002453 Handle<mirror::Class> klass, Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002454 uint32_t field_idx = it.GetMemberIndex();
2455 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002456 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002457 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002458}
2459
Brian Carlstromea46f952013-07-30 01:26:50 -07002460mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002461 const ClassDataItemIterator& it,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002462 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002463 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002464 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002465 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002466
Brian Carlstromea46f952013-07-30 01:26:50 -07002467 mirror::ArtMethod* dst = AllocArtMethod(self);
Ian Rogersa436fde2013-08-27 23:34:06 -07002468 if (UNLIKELY(dst == NULL)) {
2469 CHECK(self->IsExceptionPending()); // OOME.
2470 return NULL;
2471 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002472 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002473
Ian Rogers50b35e22012-10-04 10:09:15 -07002474 const char* old_cause = self->StartAssertNoThreadSuspension("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002475 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002476 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002477 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002478
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002479 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
Ian Rogers19846512012-02-24 11:42:47 -08002480 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002481 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002482
Ian Rogers241b5de2013-10-09 17:58:57 -07002483 uint32_t access_flags = it.GetMemberAccessFlags();
2484
Ian Rogersdfb325e2013-10-30 01:00:44 -07002485 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002486 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002487 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2488 // Void return type.
Ian Rogerscb6b0f32014-08-12 02:30:58 -07002489 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002490 klass->SetFinalizable();
2491 } else {
Ian Rogerscb6b0f32014-08-12 02:30:58 -07002492 std::string temp;
2493 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002494 // The Enum class declares a "final" finalize() method to prevent subclasses from
2495 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2496 // subclasses, so we exclude it here.
2497 // We also want to avoid setting the flag on Object, where we know that finalize() is
2498 // empty.
Ian Rogerscb6b0f32014-08-12 02:30:58 -07002499 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2500 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002501 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002502 }
2503 }
2504 }
2505 } else if (method_name[0] == '<') {
2506 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002507 bool is_init = (strcmp("<init>", method_name) == 0);
2508 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002509 if (UNLIKELY(!is_init && !is_clinit)) {
2510 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2511 } else {
2512 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2513 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002514 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002515 access_flags |= kAccConstructor;
2516 }
2517 }
2518 }
2519 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002520
Ian Rogers50b35e22012-10-04 10:09:15 -07002521 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002522 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002523}
2524
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002525void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002526 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002527 StackHandleScope<1> hs(self);
2528 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
2529 CHECK(dex_cache.Get() != NULL) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002530 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002531}
2532
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002533void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002534 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002535 CHECK(dex_cache.Get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002536 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002537 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002538}
2539
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002540bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002541 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002542 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002543 mirror::DexCache* dex_cache = GetDexCache(i);
2544 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002545 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002546 }
2547 }
2548 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002549}
2550
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002551bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002552 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002553 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002554}
2555
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002556void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002557 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002558 dex_lock_.AssertExclusiveHeld(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002559 CHECK(dex_cache.Get() != NULL) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002560 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2561 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002562 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002563 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002564 if (log_new_dex_caches_roots_) {
2565 // TODO: This is not safe if we can remove dex caches.
2566 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2567 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002568}
2569
Brian Carlstromaded5f72011-10-07 17:15:04 -07002570void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002571 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002572 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002573 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002574 if (IsDexFileRegisteredLocked(dex_file)) {
2575 return;
2576 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002577 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002578 // Don't alloc while holding the lock, since allocation may need to
2579 // suspend all threads and another thread may need the dex_lock_ to
2580 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002581 StackHandleScope<1> hs(self);
2582 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
2583 CHECK(dex_cache.Get() != NULL) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002584 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002585 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002586 if (IsDexFileRegisteredLocked(dex_file)) {
2587 return;
2588 }
2589 RegisterDexFileLocked(dex_file, dex_cache);
2590 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002591}
2592
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002593void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002594 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002595 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002596 RegisterDexFileLocked(dex_file, dex_cache);
2597}
2598
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002599mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002600 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002601 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002602 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002603 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002604 if (dex_cache->GetDexFile() == &dex_file) {
2605 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002606 }
2607 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002608 // Search matching by location name.
2609 std::string location(dex_file.GetLocation());
2610 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002611 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002612 if (dex_cache->GetDexFile()->GetLocation() == location) {
2613 return dex_cache;
2614 }
2615 }
2616 // Failure, dump diagnostic and abort.
2617 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002618 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002619 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
2620 }
2621 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002622 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002623}
2624
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002625void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002626 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08002627 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002628 mirror::DexCache* dex_cache = GetDexCache(i);
2629 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08002630 }
2631}
2632
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002633mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002634 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Ian Rogersa436fde2013-08-27 23:34:06 -07002635 if (UNLIKELY(klass == NULL)) {
2636 return NULL;
2637 }
2638 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002639}
2640
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002641mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
2642 Primitive::Type type) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002643 CHECK(primitive_class != NULL);
Ian Rogers1f539342012-10-03 21:09:42 -07002644 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002645 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002646 StackHandleScope<1> hs(self);
2647 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002648 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002649 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002650 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002651 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
2652 const char* descriptor = Primitive::Descriptor(type);
2653 mirror::Class* existing = InsertClass(descriptor, primitive_class, Hash(descriptor));
Ian Rogersc8982582012-09-07 16:53:25 -07002654 CHECK(existing == NULL) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002655 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07002656}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002657
Brian Carlstrombe977852011-07-19 14:54:54 -07002658// Create an array class (i.e. the class object for the array, not the
2659// array itself). "descriptor" looks like "[C" or "[[[[B" or
2660// "[Ljava/lang/String;".
2661//
2662// If "descriptor" refers to an array of primitives, look up the
2663// primitive type's internally-generated class object.
2664//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002665// "class_loader" is the class loader of the class that's referring to
2666// us. It's used to ensure that we're looking for the element type in
2667// the right context. It does NOT become the class loader for the
2668// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07002669//
2670// Returns NULL with an exception raised on failure.
Ian Rogers98379392014-02-24 16:53:16 -08002671mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002672 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002673 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002674 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002675 StackHandleScope<2> hs(self);
2676 Handle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1, class_loader)));
2677 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002678 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002679 // We need to accept erroneous classes as component types.
2680 component_type.Assign(LookupClass(descriptor + 1, class_loader.Get()));
2681 if (component_type.Get() == nullptr) {
2682 DCHECK(self->IsExceptionPending());
2683 return nullptr;
2684 } else {
2685 self->ClearException();
2686 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002687 }
Ian Rogers2d10b202014-05-12 19:15:18 -07002688 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
2689 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
2690 return nullptr;
2691 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002692 // See if the component type is already loaded. Array classes are
2693 // always associated with the class loader of their underlying
2694 // element type -- an array of Strings goes with the loader for
2695 // java/lang/String -- so we need to look for it there. (The
2696 // caller should have checked for the existence of the class
2697 // before calling here, but they did so with *their* class loader,
2698 // not the component type's loader.)
2699 //
2700 // If we find it, the caller adds "loader" to the class' initiating
2701 // loader list, which should prevent us from going through this again.
2702 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002703 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002704 // are the same, because our caller (FindClass) just did the
2705 // lookup. (Even if we get this wrong we still have correct behavior,
2706 // because we effectively do this lookup again when we add the new
2707 // class to the hash table --- necessary because of possible races with
2708 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002709 if (class_loader.Get() != component_type->GetClassLoader()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002710 mirror::Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002711 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002712 return new_class;
2713 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002714 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002715
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002716 // Fill out the fields in the Class.
2717 //
2718 // It is possible to execute some methods against arrays, because
2719 // all arrays are subclasses of java_lang_Object_, so we need to set
2720 // up a vtable. We can just point at the one in java_lang_Object_.
2721 //
2722 // Array classes are simple enough that we don't need to do a full
2723 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002724 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002725 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002726 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002727 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002728 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002729 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002730 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002731 } else if (strcmp(descriptor, class_roots_descriptors_[kJavaLangStringArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002732 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002733 } else if (strcmp(descriptor,
2734 class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002735 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002736 } else if (strcmp(descriptor,
2737 class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002738 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002739 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002740 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002741 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002742 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002743 }
2744 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002745 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002746 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002747 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002748 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002749 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002750 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002751 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002752 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002753 DCHECK(new_class->GetComponentType() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002754 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002755 new_class->SetSuperClass(java_lang_Object);
2756 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002757 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002758 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002759 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
2760 new_class->PopulateEmbeddedImtAndVTable();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002761 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002762 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002763 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002764
2765
2766 // All arrays have java/lang/Cloneable and java/io/Serializable as
2767 // interfaces. We need to set that up here, so that stuff like
2768 // "instanceof" works right.
2769 //
2770 // Note: The GC could run during the call to FindSystemClass,
2771 // so we need to make sure the class object is GC-valid while we're in
2772 // there. Do this by clearing the interface list so the GC will just
2773 // think that the entries are null.
2774
2775
2776 // Use the single, global copies of "interfaces" and "iftable"
2777 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002778 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002779 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002780 CHECK(array_iftable != nullptr);
2781 new_class->SetIfTable(array_iftable);
2782 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002783
Elliott Hughes00626c22013-06-14 15:04:14 -07002784 // Inherit access flags from the component type.
2785 int access_flags = new_class->GetComponentType()->GetAccessFlags();
2786 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2787 access_flags &= kAccJavaFlagsMask;
2788 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002789 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07002790 access_flags |= kAccAbstract | kAccFinal;
2791 access_flags &= ~kAccInterface;
2792
2793 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002794
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002795 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), Hash(descriptor));
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002796 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002797 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002798 }
2799 // Another thread must have loaded the class after we
2800 // started but before we finished. Abandon what we've
2801 // done.
2802 //
2803 // (Yes, this happens.)
2804
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002805 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002806}
2807
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002808mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07002809 switch (type) {
2810 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002811 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07002812 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002813 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07002814 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002815 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07002816 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002817 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07002818 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002819 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07002820 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002821 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07002822 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002823 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07002824 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002825 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07002826 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002827 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07002828 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002829 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07002830 }
Elliott Hughesbd935992011-08-22 11:59:34 -07002831 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002832 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07002833 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002834}
2835
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002836mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
2837 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002838 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002839 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08002840 std::string source;
2841 if (dex_cache != NULL) {
2842 source += " from ";
2843 source += dex_cache->GetLocation()->ToModifiedUtf8();
2844 }
2845 LOG(INFO) << "Loaded class " << descriptor << source;
2846 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002847 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07002848 mirror::Class* existing =
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002849 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002850 if (existing != NULL) {
2851 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07002852 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002853 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == NULL &&
2854 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002855 // Check a class loaded with the system class loader matches one in the image if the class
2856 // is in the image.
2857 existing = LookupClassFromImage(descriptor);
2858 if (existing != NULL) {
2859 CHECK(klass == existing);
2860 }
2861 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08002862 VerifyObject(klass);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002863 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002864 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002865 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002866 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002867 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002868}
2869
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002870mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
2871 size_t hash) {
2872 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2873 mirror::Class* existing =
2874 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
2875
2876 if (existing == nullptr) {
2877 CHECK(klass->IsProxyClass());
2878 return nullptr;
2879 }
2880
2881 CHECK_NE(existing, klass) << descriptor;
2882 CHECK(!existing->IsResolved()) << descriptor;
2883 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
2884
2885 for (auto it = class_table_.lower_bound(hash), end = class_table_.end(); it != end && it->first == hash;
2886 ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002887 mirror::Class* klass = it->second.Read();
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07002888 if (klass == existing) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002889 class_table_.erase(it);
2890 break;
2891 }
2892 }
2893
2894 CHECK(!klass->IsTemp()) << descriptor;
2895 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
2896 dex_cache_image_class_lookup_required_) {
2897 // Check a class loaded with the system class loader matches one in the image if the class
2898 // is in the image.
2899 existing = LookupClassFromImage(descriptor);
2900 if (existing != nullptr) {
2901 CHECK(klass == existing) << descriptor;
2902 }
2903 }
2904 VerifyObject(klass);
2905
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002906 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002907 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002908 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002909 }
2910
2911 return existing;
2912}
2913
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002914bool ClassLinker::RemoveClass(const char* descriptor, const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002915 size_t hash = Hash(descriptor);
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002916 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Brian Carlstromf3632832014-05-20 15:36:53 -07002917 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
2918 it != end && it->first == hash;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002919 ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002920 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002921 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002922 class_table_.erase(it);
Brian Carlstromae826982011-11-09 01:33:42 -08002923 return true;
2924 }
2925 }
2926 return false;
2927}
2928
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002929mirror::Class* ClassLinker::LookupClass(const char* descriptor,
2930 const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002931 size_t hash = Hash(descriptor);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002932 {
2933 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2934 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
2935 if (result != NULL) {
2936 return result;
2937 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07002938 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002939 if (class_loader != NULL || !dex_cache_image_class_lookup_required_) {
2940 return NULL;
2941 } else {
2942 // Lookup failed but need to search dex_caches_.
2943 mirror::Class* result = LookupClassFromImage(descriptor);
2944 if (result != NULL) {
2945 InsertClass(descriptor, result, hash);
2946 } else {
2947 // Searching the image dex files/caches failed, we don't want to get into this situation
2948 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
2949 // classes into the class table.
2950 const int32_t kMaxFailedDexCacheLookups = 1000;
2951 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
2952 MoveImageClassesToClassTable();
2953 }
2954 }
2955 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002956 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002957}
2958
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002959mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
2960 const mirror::ClassLoader* class_loader,
2961 size_t hash) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002962 auto end = class_table_.end();
2963 for (auto it = class_table_.lower_bound(hash); it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002964 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002965 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002966 if (kIsDebugBuild) {
2967 // Check for duplicates in the table.
2968 for (++it; it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002969 mirror::Class* klass2 = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002970 CHECK(!(klass2->GetClassLoader() == class_loader &&
2971 klass2->DescriptorEquals(descriptor)))
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002972 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
2973 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002974 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002975 }
Ian Rogers5d76c432011-10-31 21:42:49 -07002976 return klass;
2977 }
2978 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002979 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002980}
2981
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002982static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
2983 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2984 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
2985 CHECK(image != NULL);
2986 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
2987 return root->AsObjectArray<mirror::DexCache>();
2988}
2989
2990void ClassLinker::MoveImageClassesToClassTable() {
2991 Thread* self = Thread::Current();
2992 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2993 if (!dex_cache_image_class_lookup_required_) {
2994 return; // All dex cache classes are already in the class table.
2995 }
2996 const char* old_no_suspend_cause =
2997 self->StartAssertNoThreadSuspension("Moving image classes to class table");
2998 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogerscb6b0f32014-08-12 02:30:58 -07002999 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003000 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3001 mirror::DexCache* dex_cache = dex_caches->Get(i);
3002 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3003 for (int32_t j = 0; j < types->GetLength(); j++) {
3004 mirror::Class* klass = types->Get(j);
3005 if (klass != NULL) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003006 DCHECK(klass->GetClassLoader() == NULL);
Ian Rogerscb6b0f32014-08-12 02:30:58 -07003007 const char* descriptor = klass->GetDescriptor(&temp);
3008 size_t hash = Hash(descriptor);
3009 mirror::Class* existing = LookupClassFromTableLocked(descriptor, NULL, hash);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003010 if (existing != NULL) {
3011 CHECK(existing == klass) << PrettyClassAndClassLoader(existing) << " != "
3012 << PrettyClassAndClassLoader(klass);
3013 } else {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003014 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003015 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003016 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003017 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003018 }
3019 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003020 }
3021 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003022 dex_cache_image_class_lookup_required_ = false;
3023 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3024}
3025
3026mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
3027 Thread* self = Thread::Current();
3028 const char* old_no_suspend_cause =
3029 self->StartAssertNoThreadSuspension("Image class lookup");
3030 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3031 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3032 mirror::DexCache* dex_cache = dex_caches->Get(i);
3033 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003034 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003035 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
3036 if (string_id != NULL) {
3037 const DexFile::TypeId* type_id =
3038 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
3039 if (type_id != NULL) {
3040 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3041 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
3042 if (klass != NULL) {
3043 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3044 return klass;
3045 }
3046 }
3047 }
3048 }
3049 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3050 return NULL;
3051}
3052
3053void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3054 result.clear();
3055 if (dex_cache_image_class_lookup_required_) {
3056 MoveImageClassesToClassTable();
3057 }
3058 size_t hash = Hash(descriptor);
3059 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003060 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
Mathieu Chartier02e25112013-08-14 16:14:24 -07003061 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003062 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003063 if (klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003064 result.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003065 }
3066 }
3067}
3068
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003069void ClassLinker::VerifyClass(Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003070 // TODO: assert that the monitor on the Class is held
Ian Rogers1f539342012-10-03 21:09:42 -07003071 Thread* self = Thread::Current();
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003072 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003073
Ian Rogers9ffb0392012-09-10 11:56:50 -07003074 // Don't attempt to re-verify if already sufficiently verified.
3075 if (klass->IsVerified() ||
3076 (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler())) {
jeffhao98eacac2011-09-14 16:11:53 -07003077 return;
3078 }
3079
Ian Rogers9ffb0392012-09-10 11:56:50 -07003080 // The class might already be erroneous, for example at compile time if we attempted to verify
3081 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003082 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003083 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003084 return;
3085 }
3086
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003087 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003088 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003089 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003090 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003091 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003092 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003093 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003094 }
jeffhao98eacac2011-09-14 16:11:53 -07003095
Jeff Hao4a200f52014-04-01 14:58:49 -07003096 // Skip verification if disabled.
3097 if (!Runtime::Current()->IsVerificationEnabled()) {
3098 klass->SetStatus(mirror::Class::kStatusVerified, self);
3099 return;
3100 }
3101
Ian Rogers9ffb0392012-09-10 11:56:50 -07003102 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003103 StackHandleScope<2> hs(self);
3104 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
3105 if (super.Get() != NULL) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003106 // Acquire lock to prevent races on verifying the super class.
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003107 ObjectLock<mirror::Class> lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003108
3109 if (!super->IsVerified() && !super->IsErroneous()) {
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003110 VerifyClass(super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003111 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003112 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003113 std::string error_msg(
3114 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3115 PrettyDescriptor(klass.Get()).c_str(),
3116 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003117 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003118 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3119 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003120 self->ClearException();
3121 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003122 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3123 if (cause.Get() != nullptr) {
3124 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003125 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003126 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003127 if (Runtime::Current()->IsCompiler()) {
3128 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3129 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003130 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003131 return;
3132 }
3133 }
3134
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003135 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003136 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003137 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003138 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003139 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003140 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003141 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003142 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003143 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3144 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003145 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003146 return;
3147 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003148 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003149 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003150 if (!preverified) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003151 verifier_failure = verifier::MethodVerifier::VerifyClass(klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003152 Runtime::Current()->IsCompiler(),
3153 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003154 }
3155 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003156 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003157 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003158 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3159 << " because: " << error_msg;
3160 }
Ian Rogers1f539342012-10-03 21:09:42 -07003161 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003162 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003163 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003164 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003165 // Even though there were no verifier failures we need to respect whether the super-class
3166 // was verified or requiring runtime reverification.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003167 if (super.Get() == NULL || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003168 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003169 } else {
3170 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003171 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003172 // Pretend a soft failure occured so that we don't consider the class verified below.
3173 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003174 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003175 } else {
3176 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3177 // Soft failures at compile time should be retried at runtime. Soft
3178 // failures at runtime will be handled by slow paths in the generated
3179 // code. Set status accordingly.
3180 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003181 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003182 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003183 klass->SetStatus(mirror::Class::kStatusVerified, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003184 }
3185 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003186 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003187 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003188 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3189 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003190 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003191 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003192 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003193 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003194 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003195 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003196 // Let the interpreter know it by setting the kAccPreverified flag onto each
3197 // method.
3198 // Note: we're going here during compilation and at runtime. When we set the
3199 // kAccPreverified flag when compiling image classes, the flag is recorded
3200 // in the image and is set when loading the image.
3201 klass->SetPreverifiedFlagOnAllMethods();
3202 }
jeffhao98eacac2011-09-14 16:11:53 -07003203}
3204
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003205bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3206 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003207 // If we're compiling, we can only verify the class using the oat file if
3208 // we are not compiling the image or if the class we're verifying is not part of
3209 // the app. In other words, we will only check for preverification of bootclasspath
3210 // classes.
3211 if (Runtime::Current()->IsCompiler()) {
3212 // Are we compiling the bootclasspath?
3213 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3214 return false;
3215 }
3216 // We are compiling an app (not the image).
3217
3218 // Is this an app class? (I.e. not a bootclasspath class)
3219 if (klass->GetClassLoader() != NULL) {
3220 return false;
3221 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003222 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003223
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003224 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003225 // Make this work with gtests, which do not set up the image properly.
3226 // TODO: we should clean up gtests to set up the image path properly.
3227 if (Runtime::Current()->IsCompiler() && (oat_file == NULL)) {
3228 return false;
3229 }
3230
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003231 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07003232 uint dex_location_checksum = dex_file.GetLocationChecksum();
Ian Rogers8d31bbd2013-10-13 10:44:14 -07003233 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation().c_str(),
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07003234 &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003235 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003236 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003237 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003238 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3239 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003240 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003241 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003242 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003243 // Compile time verification failed with a soft error. Compile time verification can fail
3244 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003245 // class ... {
3246 // Foo x;
3247 // .... () {
3248 // if (...) {
3249 // v1 gets assigned a type of resolved class Foo
3250 // } else {
3251 // v1 gets assigned a type of unresolved class Bar
3252 // }
3253 // iput x = v1
3254 // } }
3255 // when we merge v1 following the if-the-else it results in Conflict
3256 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3257 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3258 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3259 // at compile time).
3260 return false;
3261 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003262 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003263 // Compile time verification failed with a hard error. This is caused by invalid instructions
3264 // in the class. These errors are unrecoverable.
3265 return false;
3266 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003267 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003268 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3269 // not loading the class.
3270 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3271 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003272 return false;
3273 }
Ian Rogerscb6b0f32014-08-12 02:30:58 -07003274 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003275 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003276 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogerscb6b0f32014-08-12 02:30:58 -07003277 << klass->GetDescriptor(&temp);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003278
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003279 return false;
3280}
3281
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003282void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003283 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003284 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3285 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3286 }
3287 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3288 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3289 }
3290}
3291
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003292void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003293 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003294 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3295 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
3296 if (code_item == NULL) {
3297 return; // native or abstract method
3298 }
3299 if (code_item->tries_size_ == 0) {
3300 return; // nothing to process
3301 }
3302 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
3303 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3304 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3305 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3306 CatchHandlerIterator iterator(handlers_ptr);
3307 for (; iterator.HasNext(); iterator.Next()) {
3308 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3309 // unresolved exception types will be ignored by exception delivery
3310 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003311 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003312 if (exception_type == NULL) {
3313 DCHECK(Thread::Current()->IsExceptionPending());
3314 Thread::Current()->ClearException();
3315 }
3316 }
3317 }
3318 handlers_ptr = iterator.EndDataPointer();
3319 }
3320}
3321
Brian Carlstromea46f952013-07-30 01:26:50 -07003322static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003323static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003324 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003325
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003326mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003327 jobjectArray interfaces, jobject loader,
3328 jobjectArray methods, jobjectArray throws) {
3329 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003330 StackHandleScope<8> hs(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003331 Handle<mirror::Class> klass(hs.NewHandle(
3332 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003333 if (klass.Get() == NULL) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003334 CHECK(self->IsExceptionPending()); // OOME.
3335 return NULL;
3336 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003337 DCHECK(klass->GetClass() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003338 klass->SetObjectSize(sizeof(mirror::Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003339 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003340 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003341 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003342 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003343 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003344 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003345 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003346
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003347 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003348 {
3349 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
3350 if (UNLIKELY(sfields == NULL)) {
3351 CHECK(self->IsExceptionPending()); // OOME.
3352 return NULL;
3353 }
3354 klass->SetSFields(sfields);
3355 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003356 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3357 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003358 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3359 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003360 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003361 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003362 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003363 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003364 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003365 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003366 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3367 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003368 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3369 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003370 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003371 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003372 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003373 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003374 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003375 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003376 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003377
Ian Rogers466bb252011-10-14 03:29:56 -07003378 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003379 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003380 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003381 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003382 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003383 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003384 }
3385 klass->SetDirectMethods(directs);
3386 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003387 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003388 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003389 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003390 }
3391 klass->SetDirectMethod(0, constructor);
3392 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003393
Mathieu Chartier590fee92013-09-13 13:46:47 -07003394 // Create virtual method using specified prototypes.
3395 size_t num_virtual_methods =
3396 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003397 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003398 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3399 num_virtual_methods);
Ian Rogersa436fde2013-08-27 23:34:06 -07003400 if (UNLIKELY(virtuals == NULL)) {
3401 CHECK(self->IsExceptionPending()); // OOME.
3402 return NULL;
3403 }
3404 klass->SetVirtualMethods(virtuals);
3405 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003406 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003407 StackHandleScope<1> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003408 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3409 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003410 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003411 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003412 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003413 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003414 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003415 }
3416 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003417 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003418
3419 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003420 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003421 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003422
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003423 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3424 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003425 {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003426 ObjectLock<mirror::Class> resolution_lock(self, klass); // Must hold lock on object when resolved.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003427 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003428 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003429 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003430 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003431 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003432 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003433 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003434 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003435
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003436 CHECK(klass->IsRetired());
3437 CHECK_NE(klass.Get(), new_class);
3438 klass.Assign(new_class);
3439
3440 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
3441 interfaces_sfield->SetObject<false>(klass.Get(), soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
3442 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
3443 throws_sfield->SetObject<false>(klass.Get(), soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
3444
3445 {
3446 // Lock on klass is released. Lock new class object.
3447 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003448 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003449 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003450
3451 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003452 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003453 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003454 CheckProxyConstructor(klass->GetDirectMethod(0));
3455 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003456 StackHandleScope<2> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003457 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3458 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003459 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003460 Handle<mirror::ArtMethod> virtual_method(hs.NewHandle(klass->GetVirtualMethod(i)));
3461 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003462 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003463
Mathieu Chartier590fee92013-09-13 13:46:47 -07003464 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003465 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003466 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003467 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3468
3469 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003470 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003471 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003472
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003473 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003474 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003475 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003476 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003477 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003478 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003479 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003480 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003481}
3482
Ian Rogersef7d42f2014-01-06 12:55:46 -08003483std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003484 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003485 mirror::String* name = proxy_class->GetName();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003486 DCHECK(name != NULL);
3487 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3488}
3489
Ian Rogersef7d42f2014-01-06 12:55:46 -08003490mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3491 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003492 DCHECK(proxy_class->IsProxyClass());
3493 DCHECK(proxy_method->IsProxyMethod());
3494 // Locate the dex cache of the original interface/Object
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003495 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003496 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003497 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003498 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003499 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003500 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003501 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003502 break;
3503 }
3504 }
3505 }
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003506 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003507 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003508 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003509 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003510 return resolved_method;
3511}
3512
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003513
Brian Carlstromea46f952013-07-30 01:26:50 -07003514mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003515 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003516 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003517 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003518 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003519 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003520 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3521 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Nicolas Geoffray167cc7c2014-07-29 08:33:44 +00003522 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3523 // code_ too)
3524 mirror::ArtMethod* constructor =
3525 down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3526 if (constructor == NULL) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003527 CHECK(self->IsExceptionPending()); // OOME.
Nicolas Geoffray167cc7c2014-07-29 08:33:44 +00003528 return NULL;
Ian Rogersa436fde2013-08-27 23:34:06 -07003529 }
Ian Rogers466bb252011-10-14 03:29:56 -07003530 // Make this constructor public and fix the class to be our Proxy version
3531 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003532 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003533 return constructor;
3534}
3535
Brian Carlstromea46f952013-07-30 01:26:50 -07003536static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003537 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003538 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003539 CHECK_STREQ(constructor->GetName(), "<init>");
3540 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3541 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003542 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003543}
3544
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003545mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003546 Handle<mirror::Class> klass,
3547 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003548 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3549 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08003550 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003551 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003552 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003553 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003554 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Ian Rogersa436fde2013-08-27 23:34:06 -07003555 if (UNLIKELY(method == NULL)) {
3556 CHECK(self->IsExceptionPending()); // OOME.
3557 return NULL;
3558 }
Ian Rogers466bb252011-10-14 03:29:56 -07003559
3560 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3561 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003562 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07003563 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003564
Ian Rogers466bb252011-10-14 03:29:56 -07003565 // At runtime the method looks like a reference and argument saving method, clone the code
3566 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003567 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
3568 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07003569 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08003570
Ian Rogersc2b44472011-12-14 21:17:17 -08003571 return method;
3572}
Jesse Wilson95caa792011-10-12 18:14:17 -04003573
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003574static void CheckProxyMethod(Handle<mirror::ArtMethod> method, Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003575 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003576 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003577 CHECK(!prototype->IsFinal());
3578 CHECK(method->IsFinal());
3579 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08003580
3581 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
3582 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
3583 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003584 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
3585 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08003586 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
3587
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003588 MethodHelper mh(method);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003589 MethodHelper mh2(prototype);
3590 CHECK_STREQ(method->GetName(), prototype->GetName());
3591 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07003592 // More complex sanity - via dex cache
Ian Rogers19846512012-02-24 11:42:47 -08003593 CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04003594}
3595
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003596static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
3597 bool can_init_parents)
3598 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003599 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003600 return true;
3601 }
3602 if (!can_init_statics) {
3603 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07003604 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003605 if (clinit != NULL) {
3606 return false;
3607 }
3608 // Check if there are encoded static values needing initialization.
3609 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003610 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003611 DCHECK(dex_class_def != NULL);
3612 if (dex_class_def->static_values_off_ != 0) {
3613 return false;
3614 }
3615 }
3616 }
3617 if (!klass->IsInterface() && klass->HasSuperClass()) {
3618 mirror::Class* super_class = klass->GetSuperClass();
3619 if (!can_init_parents && !super_class->IsInitialized()) {
3620 return false;
3621 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003622 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003623 return false;
3624 }
3625 }
3626 }
3627 return true;
3628}
3629
Mathieu Chartier590fee92013-09-13 13:46:47 -07003630bool ClassLinker::IsInitialized() const {
3631 return init_done_;
3632}
3633
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003634bool ClassLinker::InitializeClass(Handle<mirror::Class> klass, bool can_init_statics,
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003635 bool can_init_parents) {
3636 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
3637
3638 // Are we already initialized and therefore done?
3639 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
3640 // an initialized class will never change its state.
3641 if (klass->IsInitialized()) {
3642 return true;
3643 }
3644
3645 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003646 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003647 return false;
3648 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003649
Carl Shapirob5573532011-07-12 18:22:59 -07003650 Thread* self = Thread::Current();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003651 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003652 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003653 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003654
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003655 // Re-check under the lock in case another thread initialized ahead of us.
3656 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003657 return true;
3658 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003659
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003660 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003661 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003662 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromd1422f82011-09-28 11:37:09 -07003663 return false;
3664 }
3665
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003666 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003667
3668 if (!klass->IsVerified()) {
jeffhao98eacac2011-09-14 16:11:53 -07003669 VerifyClass(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003670 if (!klass->IsVerified()) {
3671 // We failed to verify, expect either the klass to be erroneous or verification failed at
3672 // compile time.
3673 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07003674 CHECK(self->IsExceptionPending());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003675 } else {
3676 CHECK(Runtime::Current()->IsCompiler());
3677 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07003678 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003679 return false;
3680 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003681 }
3682
Brian Carlstromd1422f82011-09-28 11:37:09 -07003683 // If the class is kStatusInitializing, either this thread is
3684 // initializing higher up the stack or another thread has beat us
3685 // to initializing and we need to wait. Either way, this
3686 // invocation of InitializeClass will not be responsible for
3687 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003688 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07003689 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07003690 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003691 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003692 return true;
3693 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003694 // No. That's fine. Wait for another thread to finish initializing.
3695 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003696 }
3697
3698 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003699 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003700 return false;
3701 }
3702
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003703 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003704
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003705 // From here out other threads may observe that we're initializing and so changes of state
3706 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07003707 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003708 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003709
3710 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003711 }
3712
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003713 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003714 if (!klass->IsInterface() && klass->HasSuperClass()) {
3715 mirror::Class* super_class = klass->GetSuperClass();
3716 if (!super_class->IsInitialized()) {
3717 CHECK(!super_class->IsInterface());
3718 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003719 StackHandleScope<1> hs(self);
3720 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
3721 bool super_initialized = InitializeClass(handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003722 if (!super_initialized) {
3723 // The super class was verified ahead of entering initializing, we should only be here if
3724 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003725 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07003726 << "Super class initialization failed for "
3727 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003728 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003729 << "\nPending exception:\n"
3730 << (self->GetException(NULL) != NULL ? self->GetException(NULL)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003731 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003732 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003733 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003734 return false;
3735 }
Ian Rogers1bddec32012-02-04 12:27:34 -08003736 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003737 }
3738
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003739 if (klass->NumStaticFields() > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003740 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003741 CHECK(dex_class_def != NULL);
Mathieu Chartierf8322842014-05-16 10:59:25 -07003742 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003743 StackHandleScope<2> hs(self);
3744 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07003745 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07003746 EncodedStaticFieldValueIterator it(dex_file, &dex_cache, &class_loader,
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003747 this, *dex_class_def);
3748 if (it.HasNext()) {
3749 CHECK(can_init_statics);
Brian Carlstromf3632832014-05-20 15:36:53 -07003750 // We reordered the fields, so we need to be able to map the
3751 // field indexes to the right fields.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003752 SafeMap<uint32_t, mirror::ArtField*> field_map;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003753 ConstructFieldMap(dex_file, *dex_class_def, klass.Get(), field_map);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003754 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003755 if (Runtime::Current()->IsActiveTransaction()) {
3756 it.ReadValueToField<true>(field_map.Get(i));
3757 } else {
3758 it.ReadValueToField<false>(field_map.Get(i));
3759 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003760 }
3761 }
3762 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003763
Ian Rogersd91d6d62013-09-25 20:26:14 -07003764 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003765 if (clinit != NULL) {
3766 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07003767 JValue result;
3768 clinit->Invoke(self, NULL, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003769 }
3770
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003771 uint64_t t1 = NanoTime();
3772
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003773 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003774 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003775 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003776
3777 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07003778 WrapExceptionInInitializer();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003779 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003780 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003781 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003782 RuntimeStats* global_stats = Runtime::Current()->GetStats();
3783 RuntimeStats* thread_stats = self->GetStats();
3784 ++global_stats->class_init_count;
3785 ++thread_stats->class_init_count;
3786 global_stats->class_init_time_ns += (t1 - t0);
3787 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003788 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003789 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003790 if (VLOG_IS_ON(class_linker)) {
Ian Rogerscb6b0f32014-08-12 02:30:58 -07003791 std::string temp;
3792 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07003793 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08003794 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08003795 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003796 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003797 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003798 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003799 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003800}
3801
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003802bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003803 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003804 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003805 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003806 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003807 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08003808 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003809
3810 // When we wake up, repeat the test for init-in-progress. If
3811 // there's an exception pending (only possible if
3812 // "interruptShouldThrow" was set), bail out.
3813 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07003814 WrapExceptionInInitializer();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003815 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003816 return false;
3817 }
3818 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003819 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003820 continue;
3821 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003822 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07003823 // Compile time initialization failed.
3824 return false;
3825 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003826 if (klass->IsErroneous()) {
3827 // The caller wants an exception, but it was thrown in a
3828 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07003829 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003830 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07003831 return false;
3832 }
3833 if (klass->IsInitialized()) {
3834 return true;
3835 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003836 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003837 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003838 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003839 LOG(FATAL) << "Not Reached" << PrettyClass(klass.Get());
Brian Carlstromd1422f82011-09-28 11:37:09 -07003840}
3841
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003842bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003843 if (klass->IsInterface()) {
3844 return true;
3845 }
Ian Rogers151f2212014-05-06 11:27:27 -07003846 // Begin with the methods local to the superclass.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003847 StackHandleScope<2> hs(Thread::Current());
3848 MethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
3849 MethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003850 if (klass->HasSuperClass() &&
3851 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07003852 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
3853 mh.ChangeMethod(klass->GetVTableEntry(i));
3854 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003855 if (mh.GetMethod() != super_mh.GetMethod() &&
3856 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
3857 ThrowLinkageError(klass.Get(),
3858 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003859 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07003860 PrettyMethod(mh.GetMethod()).c_str(),
3861 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003862 return false;
3863 }
3864 }
3865 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003866 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07003867 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
3868 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
3869 for (uint32_t j = 0; j < num_methods; ++j) {
3870 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
3871 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003872 if (mh.GetMethod() != super_mh.GetMethod() &&
3873 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
3874 ThrowLinkageError(klass.Get(),
3875 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003876 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07003877 PrettyMethod(mh.GetMethod()).c_str(),
3878 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003879 return false;
3880 }
3881 }
3882 }
3883 }
3884 return true;
3885}
3886
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003887bool ClassLinker::EnsureInitialized(Handle<mirror::Class> c, bool can_init_fields,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003888 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003889 DCHECK(c.Get() != nullptr);
3890 const bool success = c->IsInitialized() || InitializeClass(c, can_init_fields, can_init_parents);
3891 if (!success && can_init_fields && can_init_parents) {
3892 CHECK(Thread::Current()->IsExceptionPending()) << PrettyClass(c.Get());
Ian Rogers595799e2012-01-11 17:32:51 -08003893 }
3894 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07003895}
3896
Elliott Hughes5fe594f2011-09-08 12:33:17 -07003897void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003898 mirror::Class* c,
3899 SafeMap<uint32_t, mirror::ArtField*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07003900 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07003901 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003902 StackHandleScope<2> hs(Thread::Current());
3903 Handle<mirror::DexCache> dex_cache(hs.NewHandle(c->GetDexCache()));
3904 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(c->GetClassLoader()));
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003905 CHECK(!kMovingFields);
Ian Rogers0571d352011-11-03 19:51:38 -07003906 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003907 field_map.Put(i, ResolveField(dex_file, it.GetMemberIndex(), dex_cache, class_loader, true));
Elliott Hughes5fe594f2011-09-08 12:33:17 -07003908 }
3909}
3910
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003911void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
3912 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
3913 if (fields != nullptr) {
3914 for (int index = 0; index < fields->GetLength(); index ++) {
3915 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
3916 fields->Get(index)->SetDeclaringClass(new_class);
3917 }
3918 }
3919 }
3920
3921 fields = new_class->GetSFields();
3922 if (fields != nullptr) {
3923 for (int index = 0; index < fields->GetLength(); index ++) {
3924 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
3925 fields->Get(index)->SetDeclaringClass(new_class);
3926 }
3927 }
3928 }
3929
3930 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
3931 if (methods != nullptr) {
3932 for (int index = 0; index < methods->GetLength(); index ++) {
3933 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3934 methods->Get(index)->SetDeclaringClass(new_class);
3935 }
3936 }
3937 }
3938
3939 methods = new_class->GetVirtualMethods();
3940 if (methods != nullptr) {
3941 for (int index = 0; index < methods->GetLength(); index ++) {
3942 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3943 methods->Get(index)->SetDeclaringClass(new_class);
3944 }
3945 }
3946 }
3947}
3948
3949bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
3950 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
3951 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003952 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003953
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003954 if (!LinkSuperClass(klass)) {
3955 return false;
3956 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003957 if (!LinkMethods(self, klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003958 return false;
3959 }
3960 if (!LinkInstanceFields(klass)) {
3961 return false;
3962 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003963 size_t class_size;
3964 if (!LinkStaticFields(klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003965 return false;
3966 }
3967 CreateReferenceInstanceOffsets(klass);
3968 CreateReferenceStaticOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003969 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003970
3971 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
3972 // We don't need to retire this class as it has no embedded tables or it was created the
3973 // correct size during class linker initialization.
3974 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
3975
3976 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
3977 klass->PopulateEmbeddedImtAndVTable();
3978 }
3979
3980 // This will notify waiters on klass that saw the not yet resolved
3981 // class in the class_table_ during EnsureResolved.
3982 klass->SetStatus(mirror::Class::kStatusResolved, self);
3983 *new_class = klass.Get();
3984 } else {
3985 CHECK(!klass->IsResolved());
3986 // Retire the temporary class and create the correctly sized resolved class.
3987 *new_class = klass->CopyOf(self, class_size);
3988 if (UNLIKELY(*new_class == NULL)) {
3989 CHECK(self->IsExceptionPending()); // Expect an OOME.
3990 klass->SetStatus(mirror::Class::kStatusError, self);
3991 return false;
3992 }
3993
3994 CHECK_EQ((*new_class)->GetClassSize(), class_size);
3995 StackHandleScope<1> hs(self);
3996 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
3997 ObjectLock<mirror::Class> lock(self, new_class_h);
3998
3999 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4000
4001 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(), Hash(descriptor));
4002 CHECK(existing == NULL || existing == klass.Get());
4003
4004 // This will notify waiters on temp class that saw the not yet resolved class in the
4005 // class_table_ during EnsureResolved.
4006 klass->SetStatus(mirror::Class::kStatusRetired, self);
4007
4008 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4009 // This will notify waiters on new_class that saw the not yet resolved
4010 // class in the class_table_ during EnsureResolved.
4011 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004012 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004013 return true;
4014}
4015
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004016bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004017 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004018 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4019 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004020 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004021 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004022 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004023 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004024 return false;
4025 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004026 // Verify
4027 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004028 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004029 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004030 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004031 return false;
4032 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004033 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004034 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004035 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004036 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004037 if (interfaces != NULL) {
4038 for (size_t i = 0; i < interfaces->Size(); i++) {
4039 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004040 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004041 if (interface == NULL) {
4042 DCHECK(Thread::Current()->IsExceptionPending());
4043 return false;
4044 }
4045 // Verify
4046 if (!klass->CanAccess(interface)) {
4047 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004048 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004049 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004050 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004051 return false;
4052 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004053 }
4054 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004055 // Mark the class as loaded.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004056 klass->SetStatus(mirror::Class::kStatusLoaded, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004057 return true;
4058}
4059
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004060bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004061 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004062 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004063 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004064 if (super != NULL) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004065 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004066 return false;
4067 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004068 return true;
4069 }
4070 if (super == NULL) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004071 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4072 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004073 return false;
4074 }
4075 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004076 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004077 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004078 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004079 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004080 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004081 return false;
4082 }
4083 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004084 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004085 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004086 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004087 return false;
4088 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004089
Brian Carlstromf3632832014-05-20 15:36:53 -07004090 // Inherit kAccClassIsFinalizable from the superclass in case this
4091 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004092 if (super->IsFinalizable()) {
4093 klass->SetFinalizable();
4094 }
4095
Elliott Hughes2da50362011-10-10 16:57:08 -07004096 // Inherit reference flags (if any) from the superclass.
4097 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4098 if (reference_flags != 0) {
4099 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4100 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004101 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004102 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004103 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004104 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004105 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004106 return false;
4107 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004108
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004109 if (kIsDebugBuild) {
4110 // Ensure super classes are fully resolved prior to resolving fields..
4111 while (super != NULL) {
4112 CHECK(super->IsResolved());
4113 super = super->GetSuperClass();
4114 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004115 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004116 return true;
4117}
4118
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004119// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004120bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004121 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004122 if (klass->IsInterface()) {
4123 // No vtable.
4124 size_t count = klass->NumVirtualMethods();
4125 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004126 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004127 return false;
4128 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004129 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004130 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004131 }
jeffhaobdb76512011-09-07 11:43:16 -07004132 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004133 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004134 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07004135 // Link virtual and interface method tables
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004136 return LinkVirtualMethods(self, klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004137 }
4138 return true;
4139}
4140
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004141bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004142 if (klass->HasSuperClass()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004143 uint32_t max_count = klass->NumVirtualMethods() +
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004144 klass->GetSuperClass()->GetVTableLength();
4145 size_t actual_count = klass->GetSuperClass()->GetVTableLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004146 CHECK_LE(actual_count, max_count);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004147 StackHandleScope<3> hs(self);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004148 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
4149 mirror::Class* super_class = klass->GetSuperClass();
4150 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4151 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4152 if (UNLIKELY(vtable.Get() == nullptr)) {
4153 CHECK(self->IsExceptionPending()); // OOME.
4154 return false;
4155 }
4156 int len = super_class->GetVTableLength();
Mingyao Yang1a128582014-07-22 17:33:25 -07004157 for (int i = 0; i < len; i++) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004158 vtable->Set<false>(i, super_class->GetVTableEntry(i));
4159 }
4160 } else {
4161 CHECK(super_class->GetVTable() != nullptr) << PrettyClass(super_class);
4162 vtable = hs.NewHandle(super_class->GetVTable()->CopyOf(self, max_count));
4163 if (UNLIKELY(vtable.Get() == nullptr)) {
4164 CHECK(self->IsExceptionPending()); // OOME.
4165 return false;
4166 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004167 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004168
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004169 // See if any of our virtual methods override the superclass.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004170 MethodHelper local_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4171 MethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004172 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004173 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004174 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004175 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004176 for (; j < actual_count; ++j) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004177 mirror::ArtMethod* super_method = vtable->Get(j);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004178 super_mh.ChangeMethod(super_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004179 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004180 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4181 super_method->GetAccessFlags())) {
Elliott Hughes39717372012-07-13 16:21:23 -07004182 if (super_method->IsFinal()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004183 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
Elliott Hughes39717372012-07-13 16:21:23 -07004184 PrettyMethod(local_method).c_str(),
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004185 super_method->GetDeclaringClassDescriptor());
Elliott Hughes39717372012-07-13 16:21:23 -07004186 return false;
4187 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004188 vtable->Set<false>(j, local_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004189 local_method->SetMethodIndex(j);
4190 break;
4191 } else {
4192 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method)
4193 << " would have incorrectly overridden the package-private method in "
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004194 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004195 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004196 }
4197 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004198 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004199 // Not overriding, append.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004200 vtable->Set<false>(actual_count, local_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004201 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004202 actual_count += 1;
4203 }
4204 }
4205 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004206 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004207 return false;
4208 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004209 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004210 CHECK_LE(actual_count, max_count);
4211 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004212 vtable.Assign(vtable->CopyOf(self, actual_count));
4213 if (UNLIKELY(vtable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004214 CHECK(self->IsExceptionPending()); // OOME.
4215 return false;
4216 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004217 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004218 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004219 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004220 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004221 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004222 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004223 ThrowClassFormatError(klass.Get(), "Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004224 return false;
4225 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004226 StackHandleScope<1> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004227 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004228 vtable(hs.NewHandle(AllocArtMethodArray(self, num_virtual_methods)));
4229 if (UNLIKELY(vtable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004230 CHECK(self->IsExceptionPending()); // OOME.
4231 return false;
4232 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004233 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004234 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004235 vtable->Set<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004236 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004237 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004238 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004239 }
4240 return true;
4241}
4242
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004243bool ClassLinker::LinkInterfaceMethods(Handle<mirror::Class> klass,
4244 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004245 Thread* const self = Thread::Current();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004246 Runtime* const runtime = Runtime::Current();
Jeff Hao88474b42013-10-23 16:24:40 -07004247 // Set the imt table to be all conflicts by default.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004248 klass->SetImTable(runtime->GetDefaultImt());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004249 size_t super_ifcount;
4250 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004251 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004252 } else {
4253 super_ifcount = 0;
4254 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07004255 uint32_t num_interfaces =
4256 interfaces.Get() == nullptr ? klass->NumDirectInterfaces() : interfaces->GetLength();
4257 size_t ifcount = super_ifcount + num_interfaces;
4258 for (size_t i = 0; i < num_interfaces; i++) {
4259 mirror::Class* interface =
4260 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4261 interfaces->Get(i);
4262 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004263 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004264 if (ifcount == 0) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004265 // Class implements no interfaces.
4266 DCHECK_EQ(klass->GetIfTableCount(), 0);
4267 DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004268 return true;
4269 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004270 if (ifcount == super_ifcount) {
4271 // Class implements same interfaces as parent, are any of these not marker interfaces?
4272 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004273 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Ian Rogers9bc81912012-10-11 21:43:36 -07004274 for (size_t i = 0; i < ifcount; ++i) {
4275 if (super_iftable->GetMethodArrayCount(i) > 0) {
4276 has_non_marker_interface = true;
4277 break;
4278 }
4279 }
4280 if (!has_non_marker_interface) {
4281 // Class just inherits marker interfaces from parent so recycle parent's iftable.
4282 klass->SetIfTable(super_iftable);
4283 return true;
4284 }
4285 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004286 StackHandleScope<4> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004287 Handle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
4288 if (UNLIKELY(iftable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004289 CHECK(self->IsExceptionPending()); // OOME.
4290 return false;
4291 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004292 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004293 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004294 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004295 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004296 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004297 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004298 }
4299 // Flatten the interface inheritance hierarchy.
4300 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004301 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004302 mirror::Class* interface =
Mathieu Chartierf8322842014-05-16 10:59:25 -07004303 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4304 interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004305 DCHECK(interface != NULL);
4306 if (!interface->IsInterface()) {
Ian Rogerscb6b0f32014-08-12 02:30:58 -07004307 std::string temp;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004308 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4309 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogerscb6b0f32014-08-12 02:30:58 -07004310 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004311 return false;
4312 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004313 // Check if interface is already in iftable
4314 bool duplicate = false;
4315 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004316 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004317 if (existing_interface == interface) {
4318 duplicate = true;
4319 break;
4320 }
4321 }
4322 if (!duplicate) {
4323 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004324 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004325 // Add this interface's non-duplicate super-interfaces.
4326 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004327 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004328 bool super_duplicate = false;
4329 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004330 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004331 if (existing_interface == super_interface) {
4332 super_duplicate = true;
4333 break;
4334 }
4335 }
4336 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004337 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004338 }
4339 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004340 }
4341 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004342 // Shrink iftable in case duplicates were found
4343 if (idx < ifcount) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004344 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
4345 if (UNLIKELY(iftable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004346 CHECK(self->IsExceptionPending()); // OOME.
4347 return false;
4348 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004349 ifcount = idx;
4350 } else {
4351 CHECK_EQ(idx, ifcount);
4352 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004353 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004354
4355 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004356 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004357 return true;
4358 }
Jeff Hao88474b42013-10-23 16:24:40 -07004359 // Allocate imtable
4360 bool imtable_changed = false;
Ian Rogers700a4022014-05-19 16:49:03 -07004361 Handle<mirror::ObjectArray<mirror::ArtMethod>> imtable(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004362 hs.NewHandle(AllocArtMethodArray(self, mirror::Class::kImtSize)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004363 if (UNLIKELY(imtable.Get() == NULL)) {
Jeff Hao88474b42013-10-23 16:24:40 -07004364 CHECK(self->IsExceptionPending()); // OOME.
4365 return false;
4366 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004367 MethodHelper interface_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4368 MethodHelper vtable_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Brian Carlstromea46f952013-07-30 01:26:50 -07004369 std::vector<mirror::ArtMethod*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004370 for (size_t i = 0; i < ifcount; ++i) {
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004371 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004372 if (num_methods > 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004373 StackHandleScope<2> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004374 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004375 method_array(hs.NewHandle(AllocArtMethodArray(self, num_methods)));
4376 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004377 CHECK(self->IsExceptionPending()); // OOME.
4378 return false;
4379 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004380 iftable->SetMethodArray(i, method_array.Get());
Ian Rogers700a4022014-05-19 16:49:03 -07004381 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004382 hs.NewHandle(klass->GetVTableDuringLinking()));
Ian Rogers62d6c772013-02-27 08:32:07 -08004383 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004384 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004385 interface_mh.ChangeMethod(interface_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004386 int32_t k;
4387 // For each method listed in the interface's method list, find the
4388 // matching method in our class's method list. We want to favor the
4389 // subclass over the superclass, which just requires walking
4390 // back from the end of the vtable. (This only matters if the
4391 // superclass defines a private method and this class redefines
4392 // it -- otherwise it would use the same vtable slot. In .dex files
4393 // those don't end up in the virtual method table, so it shouldn't
4394 // matter which direction we go. We walk it backward anyway.)
4395 for (k = vtable->GetLength() - 1; k >= 0; --k) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004396 mirror::ArtMethod* vtable_method = vtable->Get(k);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004397 vtable_mh.ChangeMethod(vtable_method);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004398 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Elliott Hughes68243612013-02-22 17:16:07 -08004399 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004400 ThrowIllegalAccessError(
4401 klass.Get(),
4402 "Method '%s' implementing interface method '%s' is not public",
4403 PrettyMethod(vtable_method).c_str(),
4404 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004405 return false;
4406 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004407 method_array->Set<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004408 // Place method in imt if entry is empty, place conflict otherwise.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004409 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
Jeff Hao88474b42013-10-23 16:24:40 -07004410 if (imtable->Get(imt_index) == NULL) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004411 imtable->Set<false>(imt_index, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004412 imtable_changed = true;
4413 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004414 imtable->Set<false>(imt_index, runtime->GetImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -07004415 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004416 break;
4417 }
4418 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004419 if (k < 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004420 StackHandleScope<1> hs(self);
4421 auto miranda_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004422 for (mirror::ArtMethod* mir_method : miranda_list) {
4423 vtable_mh.ChangeMethod(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004424 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004425 miranda_method.Assign(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004426 break;
4427 }
4428 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004429 if (miranda_method.Get() == NULL) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004430 // Point the interface table at a phantom slot.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004431 miranda_method.Assign(down_cast<mirror::ArtMethod*>(interface_method->Clone(self)));
4432 if (UNLIKELY(miranda_method.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004433 CHECK(self->IsExceptionPending()); // OOME.
4434 return false;
4435 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004436 // TODO: If a methods move then the miranda_list may hold stale references.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004437 miranda_list.push_back(miranda_method.Get());
Ian Rogers9bc81912012-10-11 21:43:36 -07004438 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004439 method_array->Set<false>(j, miranda_method.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004440 }
4441 }
4442 }
4443 }
Jeff Hao88474b42013-10-23 16:24:40 -07004444 if (imtable_changed) {
4445 // Fill in empty entries in interface method table with conflict.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004446 mirror::ArtMethod* imt_conflict_method = runtime->GetImtConflictMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004447 for (size_t i = 0; i < mirror::Class::kImtSize; i++) {
Jeff Hao88474b42013-10-23 16:24:40 -07004448 if (imtable->Get(i) == NULL) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004449 imtable->Set<false>(i, imt_conflict_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004450 }
4451 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004452 klass->SetImTable(imtable.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004453 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004454 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004455 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07004456 int new_method_count = old_method_count + miranda_list.size();
Ian Rogersa436fde2013-08-27 23:34:06 -07004457 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4458 if (old_method_count == 0) {
4459 virtuals = AllocArtMethodArray(self, new_method_count);
4460 } else {
4461 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4462 }
4463 if (UNLIKELY(virtuals == NULL)) {
4464 CHECK(self->IsExceptionPending()); // OOME.
4465 return false;
4466 }
4467 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004468
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004469 StackHandleScope<1> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004470 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004471 hs.NewHandle(klass->GetVTableDuringLinking()));
4472 CHECK(vtable.Get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004473 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07004474 int new_vtable_count = old_vtable_count + miranda_list.size();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004475 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
4476 if (UNLIKELY(vtable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004477 CHECK(self->IsExceptionPending()); // OOME.
4478 return false;
4479 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004480 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004481 mirror::ArtMethod* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07004482 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07004483 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4484 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4485 klass->SetVirtualMethod(old_method_count + i, method);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004486 vtable->Set<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004487 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004488 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004489 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004490 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004491
Brian Carlstromea46f952013-07-30 01:26:50 -07004492 mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking();
Elliott Hughes4681c802011-09-25 18:04:37 -07004493 for (int i = 0; i < vtable->GetLength(); ++i) {
4494 CHECK(vtable->Get(i) != NULL);
4495 }
4496
4497// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
4498
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004499 return true;
4500}
4501
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004502bool ClassLinker::LinkInstanceFields(Handle<mirror::Class> klass) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004503 CHECK(klass.Get() != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004504 return LinkFields(klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004505}
4506
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004507bool ClassLinker::LinkStaticFields(Handle<mirror::Class> klass, size_t* class_size) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004508 CHECK(klass.Get() != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004509 return LinkFields(klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004510}
4511
Brian Carlstromdbc05252011-09-09 01:59:59 -07004512struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004513 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4514 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004515 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004516 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004517 NO_THREAD_SAFETY_ANALYSIS {
Brian Carlstromdbc05252011-09-09 01:59:59 -07004518 // First come reference fields, then 64-bit, and finally 32-bit
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004519 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
4520 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08004521 if (type1 != type2) {
4522 bool is_primitive1 = type1 != Primitive::kPrimNot;
4523 bool is_primitive2 = type2 != Primitive::kPrimNot;
Brian Carlstromf3632832014-05-20 15:36:53 -07004524 bool is64bit1 = is_primitive1 && (type1 == Primitive::kPrimLong ||
4525 type1 == Primitive::kPrimDouble);
4526 bool is64bit2 = is_primitive2 && (type2 == Primitive::kPrimLong ||
4527 type2 == Primitive::kPrimDouble);
Ian Rogersef7d42f2014-01-06 12:55:46 -08004528 int order1 = !is_primitive1 ? 0 : (is64bit1 ? 1 : 2);
4529 int order2 = !is_primitive2 ? 0 : (is64bit2 ? 1 : 2);
4530 if (order1 != order2) {
4531 return order1 < order2;
4532 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07004533 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07004534 // same basic group? then sort by string.
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004535 return strcmp(field1->GetName(), field2->GetName()) < 0;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004536 }
4537};
4538
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004539bool ClassLinker::LinkFields(Handle<mirror::Class> klass, bool is_static, size_t* class_size) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004540 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004541 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004542
Brian Carlstromea46f952013-07-30 01:26:50 -07004543 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004544 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004545
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004546 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07004547 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004548 if (is_static) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004549 uint32_t base = sizeof(mirror::Class); // Static fields come after the class.
4550 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
4551 // Static fields come after the embedded tables.
4552 base = mirror::Class::ComputeClassSize(true, klass->GetVTableDuringLinking()->GetLength(),
4553 0, 0, 0);
4554 }
4555 field_offset = MemberOffset(base);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004556 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004557 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004558 if (super_class != NULL) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004559 CHECK(super_class->IsResolved())
4560 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004561 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004562 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004563 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004564
Brian Carlstromf3632832014-05-20 15:36:53 -07004565 CHECK_EQ(num_fields == 0, fields == NULL) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004566
Brian Carlstromdbc05252011-09-09 01:59:59 -07004567 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07004568 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07004569 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004570 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004571 mirror::ArtField* f = fields->Get(i);
Brian Carlstromf3632832014-05-20 15:36:53 -07004572 CHECK(f != NULL) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004573 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004574 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07004575 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
4576 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07004577
4578 // References should be at the front.
4579 size_t current_field = 0;
4580 size_t num_reference_fields = 0;
4581 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004582 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004583 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004584 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004585 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004586 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004587 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07004588 grouped_and_sorted_fields.pop_front();
4589 num_reference_fields++;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004590 fields->Set<false>(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004591 field->SetOffset(field_offset);
4592 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004593 }
4594
4595 // Now we want to pack all of the double-wide fields together. If
4596 // we're not aligned, though, we want to shuffle one 32-bit field
4597 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07004598 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07004599 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004600 mirror::ArtField* field = grouped_and_sorted_fields[i];
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004601 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstromf3632832014-05-20 15:36:53 -07004602 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004603 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07004604 continue;
4605 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004606 fields->Set<false>(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004607 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004608 // drop the consumed field
4609 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
4610 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004611 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07004612 // whether we found a 32-bit field for padding or not, we advance
4613 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004614 }
4615
4616 // Alignment is good, shuffle any double-wide fields forward, and
4617 // finish assigning field offsets to all fields.
Brian Carlstromf3632832014-05-20 15:36:53 -07004618 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()))
4619 << PrettyClass(klass.Get());
Brian Carlstromdbc05252011-09-09 01:59:59 -07004620 while (!grouped_and_sorted_fields.empty()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004621 mirror::ArtField* field = grouped_and_sorted_fields.front();
Brian Carlstromdbc05252011-09-09 01:59:59 -07004622 grouped_and_sorted_fields.pop_front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004623 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstromf3632832014-05-20 15:36:53 -07004624 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004625 fields->Set<false>(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004626 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004627 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004628 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07004629 ? sizeof(uint64_t)
4630 : sizeof(uint32_t)));
4631 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004632 }
4633
Elliott Hughesadb460d2011-10-05 17:02:34 -07004634 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it.
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004635 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07004636 // We know there are no non-reference fields in the Reference classes, and we know
4637 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07004638 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004639 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07004640 --num_reference_fields;
4641 }
4642
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004643 if (kIsDebugBuild) {
4644 // Make sure that all reference fields appear before
4645 // non-reference fields, and all double-wide fields are aligned.
4646 bool seen_non_ref = false;
4647 for (size_t i = 0; i < num_fields; i++) {
4648 mirror::ArtField* field = fields->Get(i);
4649 if (false) { // enable to debug field layout
4650 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004651 << " class=" << PrettyClass(klass.Get())
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004652 << " field=" << PrettyField(field)
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07004653 << " offset="
4654 << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004655 }
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004656 Primitive::Type type = field->GetTypeAsPrimitiveType();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004657 bool is_primitive = type != Primitive::kPrimNot;
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004658 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004659 strcmp("referent", field->GetName()) == 0) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004660 is_primitive = true; // We lied above, so we have to expect a lie here.
4661 }
4662 if (is_primitive) {
4663 if (!seen_non_ref) {
4664 seen_non_ref = true;
Brian Carlstromf3632832014-05-20 15:36:53 -07004665 DCHECK_EQ(num_reference_fields, i) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004666 }
4667 } else {
Brian Carlstromf3632832014-05-20 15:36:53 -07004668 DCHECK(!seen_non_ref) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004669 }
4670 }
4671 if (!seen_non_ref) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004672 DCHECK_EQ(num_fields, num_reference_fields) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004673 }
4674 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004675
4676 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004677 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004678 if (is_static) {
4679 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004680 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004681 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004682 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004683 if (!klass->IsVariableSize()) {
Ian Rogerscb6b0f32014-08-12 02:30:58 -07004684 std::string temp;
4685 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07004686 size_t previous_size = klass->GetObjectSize();
4687 if (previous_size != 0) {
4688 // Make sure that we didn't originally have an incorrect size.
Ian Rogerscb6b0f32014-08-12 02:30:58 -07004689 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07004690 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004691 klass->SetObjectSize(size);
4692 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004693 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004694 return true;
4695}
4696
4697// Set the bitmap of reference offsets, refOffsets, from the ifields
4698// list.
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004699void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004700 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004701 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004702 if (super_class != NULL) {
4703 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07004704 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004705 if (reference_offsets == CLASS_WALK_SUPER) {
4706 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004707 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004708 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004709 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004710 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004711}
4712
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004713void ClassLinker::CreateReferenceStaticOffsets(Handle<mirror::Class> klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004714 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004715}
4716
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004717void ClassLinker::CreateReferenceOffsets(Handle<mirror::Class> klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004718 uint32_t reference_offsets) {
4719 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004720 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
4721 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogersef7d42f2014-01-06 12:55:46 -08004722 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004723 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07004724 // All of the fields that contain object references are guaranteed
4725 // to be at the beginning of the fields list.
4726 for (size_t i = 0; i < num_reference_fields; ++i) {
4727 // Note that byte_offset is the offset from the beginning of
4728 // object, not the offset into instance data
Ian Rogersef7d42f2014-01-06 12:55:46 -08004729 mirror::ArtField* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004730 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004731 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
4732 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
4733 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07004734 CHECK_NE(new_bit, 0U);
4735 reference_offsets |= new_bit;
4736 } else {
4737 reference_offsets = CLASS_WALK_SUPER;
4738 break;
4739 }
4740 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004741 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004742 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004743 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004744 } else {
4745 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004746 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004747}
4748
Mathieu Chartier590fee92013-09-13 13:46:47 -07004749mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004750 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004751 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004752 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004753 if (resolved != NULL) {
4754 return resolved;
4755 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07004756 uint32_t utf16_length;
4757 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004758 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004759 dex_cache->SetResolvedString(string_idx, string);
4760 return string;
4761}
4762
Mathieu Chartier590fee92013-09-13 13:46:47 -07004763mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08004764 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004765 StackHandleScope<2> hs(Thread::Current());
4766 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
4767 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07004768 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
4769}
4770
4771mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004772 Handle<mirror::DexCache> dex_cache,
4773 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004774 DCHECK(dex_cache.Get() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004775 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004776 if (resolved == NULL) {
Ian Rogers98379392014-02-24 16:53:16 -08004777 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07004778 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08004779 resolved = FindClass(self, descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004780 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05004781 // TODO: we used to throw here if resolved's class loader was not the
4782 // boot class loader. This was to permit different classes with the
4783 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004784 dex_cache->SetResolvedType(type_idx, resolved);
4785 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08004786 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08004787 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08004788 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004789 StackHandleScope<1> hs(self);
4790 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08004791 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004792 DCHECK(resolved == NULL); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08004793 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08004794 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004795 self->GetException(NULL)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08004796 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004797 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004798 }
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07004799 DCHECK((resolved == NULL) || resolved->IsResolved() || resolved->IsErroneous())
4800 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004801 return resolved;
4802}
4803
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004804mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
4805 Handle<mirror::DexCache> dex_cache,
4806 Handle<mirror::ClassLoader> class_loader,
4807 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07004808 InvokeType type) {
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004809 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07004810 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07004811 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004812 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004813 return resolved;
4814 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004815 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004816 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004817 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004818 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07004819 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004820 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004821 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004822 // Scan using method_idx, this saves string compares but will only hit for matching dex
4823 // caches/files.
4824 switch (type) {
4825 case kDirect: // Fall-through.
4826 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004827 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004828 break;
4829 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004830 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004831 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004832 break;
4833 case kSuper: // Fall-through.
4834 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004835 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004836 break;
4837 default:
4838 LOG(FATAL) << "Unreachable - invocation type: " << type;
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004839 }
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004840 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004841 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004842 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07004843 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07004844 switch (type) {
4845 case kDirect: // Fall-through.
4846 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08004847 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07004848 break;
4849 case kInterface:
4850 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004851 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004852 break;
4853 case kSuper: // Fall-through.
4854 case kVirtual:
4855 resolved = klass->FindVirtualMethod(name, signature);
4856 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004857 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004858 }
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004859 // If we found a method, check for incompatible class changes.
4860 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004861 // Be a good citizen and update the dex cache to speed subsequent calls.
4862 dex_cache->SetResolvedMethod(method_idx, resolved);
4863 return resolved;
4864 } else {
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004865 // If we had a method, it's an incompatible-class-change error.
4866 if (resolved != nullptr) {
4867 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
4868 } else {
4869 // We failed to find the method which means either an access error, an incompatible class
4870 // change, or no such method. First try to find the method among direct and virtual methods.
4871 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
4872 const Signature signature = dex_file.GetMethodSignature(method_id);
4873 switch (type) {
4874 case kDirect:
4875 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07004876 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004877 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
4878 // have had a resolved method before, which triggers the "true" branch above.
4879 break;
4880 case kInterface:
4881 case kVirtual:
4882 case kSuper:
4883 resolved = klass->FindDirectMethod(name, signature);
4884 break;
4885 }
4886
4887 // If we found something, check that it can be accessed by the referrer.
4888 if (resolved != nullptr && referrer.Get() != nullptr) {
4889 mirror::Class* methods_class = resolved->GetDeclaringClass();
4890 mirror::Class* referring_class = referrer->GetDeclaringClass();
4891 if (!referring_class->CanAccess(methods_class)) {
4892 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
4893 resolved, type);
4894 return nullptr;
4895 } else if (!referring_class->CanAccessMember(methods_class,
4896 resolved->GetAccessFlags())) {
4897 ThrowIllegalAccessErrorMethod(referring_class, resolved);
4898 return nullptr;
4899 }
4900 }
4901
4902 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
4903 // methods and throw if we find the method there. If we find nothing, throw a
4904 // NoSuchMethodError.
4905 switch (type) {
4906 case kDirect:
4907 case kStatic:
4908 if (resolved != nullptr) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004909 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07004910 } else {
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004911 resolved = klass->FindInterfaceMethod(name, signature);
4912 if (resolved != nullptr) {
4913 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
4914 } else {
4915 ThrowNoSuchMethodError(type, klass, name, signature);
4916 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004917 }
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004918 break;
4919 case kInterface:
4920 if (resolved != nullptr) {
4921 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07004922 } else {
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004923 resolved = klass->FindVirtualMethod(name, signature);
4924 if (resolved != nullptr) {
4925 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
4926 } else {
4927 ThrowNoSuchMethodError(type, klass, name, signature);
4928 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004929 }
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004930 break;
4931 case kSuper:
4932 ThrowNoSuchMethodError(type, klass, name, signature);
4933 break;
4934 case kVirtual:
4935 if (resolved != nullptr) {
4936 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
4937 } else {
4938 resolved = klass->FindInterfaceMethod(name, signature);
4939 if (resolved != nullptr) {
4940 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
4941 } else {
4942 ThrowNoSuchMethodError(type, klass, name, signature);
4943 }
4944 }
4945 break;
4946 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004947 }
4948 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004949 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07004950 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004951}
4952
Mathieu Chartier590fee92013-09-13 13:46:47 -07004953mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004954 Handle<mirror::DexCache> dex_cache,
4955 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07004956 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004957 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07004958 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe4ef12f52014-07-31 16:23:49 -07004959 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004960 return resolved;
4961 }
4962 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004963 Thread* const self = Thread::Current();
4964 StackHandleScope<1> hs(self);
4965 Handle<mirror::Class> klass(
4966 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe4ef12f52014-07-31 16:23:49 -07004967 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08004968 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe4ef12f52014-07-31 16:23:49 -07004969 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004970 }
4971
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004972 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004973 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004974 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004975 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004976 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004977
Andreas Gampe4ef12f52014-07-31 16:23:49 -07004978 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004979 const char* name = dex_file.GetFieldName(field_id);
4980 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
4981 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004982 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004983 } else {
4984 resolved = klass->FindInstanceField(name, type);
4985 }
Andreas Gampe4ef12f52014-07-31 16:23:49 -07004986 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004987 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004988 return NULL;
4989 }
Ian Rogersb067ac22011-12-13 18:05:09 -08004990 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004991 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08004992 return resolved;
4993}
4994
Brian Carlstromea46f952013-07-30 01:26:50 -07004995mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004996 uint32_t field_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004997 Handle<mirror::DexCache> dex_cache,
4998 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004999 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005000 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005001 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005002 return resolved;
5003 }
5004 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005005 Thread* self = Thread::Current();
5006 StackHandleScope<1> hs(self);
5007 Handle<mirror::Class> klass(
5008 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
5009 if (klass.Get() == NULL) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005010 DCHECK(Thread::Current()->IsExceptionPending());
5011 return NULL;
5012 }
5013
Ian Rogersdfb325e2013-10-30 01:00:44 -07005014 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5015 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005016 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005017 resolved = mirror::Class::FindField(self, klass, name, type);
Ian Rogersb067ac22011-12-13 18:05:09 -08005018 if (resolved != NULL) {
5019 dex_cache->SetResolvedField(field_idx, resolved);
5020 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005021 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005022 }
5023 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005024}
5025
Brian Carlstromea46f952013-07-30 01:26:50 -07005026const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005027 uint32_t* length) {
5028 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5029 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005030 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005031 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005032 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005033}
5034
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005035void ClassLinker::DumpAllClasses(int flags) {
5036 if (dex_cache_image_class_lookup_required_) {
5037 MoveImageClassesToClassTable();
5038 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005039 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5040 // lock held, because it might need to resolve a field's type, which would try to take the lock.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005041 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005042 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005043 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005044 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
5045 mirror::Class* klass = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07005046 all_classes.push_back(klass);
Ian Rogers5d76c432011-10-31 21:42:49 -07005047 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005048 }
5049
5050 for (size_t i = 0; i < all_classes.size(); ++i) {
5051 all_classes[i]->DumpClass(std::cerr, flags);
5052 }
5053}
5054
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005055void ClassLinker::DumpForSigQuit(std::ostream& os) {
5056 if (dex_cache_image_class_lookup_required_) {
5057 MoveImageClassesToClassTable();
5058 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005059 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005060 os << "Loaded classes: " << class_table_.size() << " allocated classes\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005061}
5062
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005063size_t ClassLinker::NumLoadedClasses() {
5064 if (dex_cache_image_class_lookup_required_) {
5065 MoveImageClassesToClassTable();
5066 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005067 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005068 return class_table_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005069}
5070
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005071pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005072 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005073}
5074
5075pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005076 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005077}
5078
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005079void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005080 DCHECK(!init_done_);
5081
5082 DCHECK(klass != NULL);
5083 DCHECK(klass->GetClassLoader() == NULL);
5084
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005085 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005086 DCHECK(class_roots != NULL);
5087 DCHECK(class_roots->Get(class_root) == NULL);
5088 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005089}
5090
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005091} // namespace art