blob: 7494615790915ff37a53dfa3fb2b6d3ee19ce407 [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 }
Alex Light0a112bb2014-08-14 14:16:26 -0700857 // If the file isn't executable we failed patchoat but did manage to get the dex files.
858 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700859 } else {
860 if (needs_registering) {
861 // We opened it, delete it.
862 open_oat_file.reset();
863 } else {
864 open_oat_file.release(); // Do not delete open oat files.
865 }
866 }
867
868 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
869
870 // Need a checksum, fail else.
871 if (!have_checksum) {
872 error_msgs->push_back(checksum_error_msg);
873 return false;
874 }
875
876 // Look in cache location if no oat_location is given.
877 std::string cache_location;
878 if (oat_location == nullptr) {
879 // Use the dalvik cache.
880 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
881 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
882 oat_location = cache_location.c_str();
883 }
884
885 // Definitely need to lock now.
886 if (!scoped_flock.HasFile()) {
887 std::string error_msg;
888 if (!scoped_flock.Init(oat_location, &error_msg)) {
889 error_msgs->push_back(error_msg);
890 return false;
891 }
892 }
893
Nicolas Geoffray9c290012014-07-22 10:48:00 +0100894 if (Runtime::Current()->IsDex2OatEnabled()) {
895 // Create the oat file.
896 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
897 oat_location, error_msgs));
898 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700899
900 // Failed, bail.
901 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray9c290012014-07-22 10:48:00 +0100902 std::string error_msg;
903 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
904 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
905 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -0700906 return false;
907 }
908
909 // Try to load again, but stronger checks.
910 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location, true, error_msgs,
911 dex_files);
912 if (success) {
913 RegisterOatFile(open_oat_file.release());
914 return true;
915 } else {
916 return false;
917 }
918}
919
920const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
921 uint32_t dex_location_checksum,
922 const char* oat_location,
923 std::string* error_msg) {
Ian Rogers700a4022014-05-19 16:49:03 -0700924 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, NULL,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700925 !Runtime::Current()->IsCompiler(),
926 error_msg));
927 if (oat_file.get() == nullptr) {
928 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
929 error_msg->c_str());
930 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800931 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700932 Runtime* runtime = Runtime::Current();
933 const ImageHeader& image_header = runtime->GetHeap()->GetImageSpace()->GetImageHeader();
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700934 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
935 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
936 if (expected_image_oat_checksum != actual_image_oat_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700937 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
938 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
939 actual_image_oat_checksum);
940 return nullptr;
Brian Carlstrom28db0122012-10-18 16:20:41 -0700941 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700942
Ian Rogersef7d42f2014-01-06 12:55:46 -0800943 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700944 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
945 if (expected_image_oat_offset != actual_image_oat_offset) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800946 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
947 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700948 actual_image_oat_offset);
949 return nullptr;
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700950 }
Alex Lighta59dd802014-07-02 16:28:08 -0700951 int32_t expected_patch_delta = image_header.GetPatchDelta();
952 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
953 if (expected_patch_delta != actual_patch_delta) {
954 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
955 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
956 return nullptr;
957 }
Vladimir Marko64e7ac02014-05-01 15:43:47 +0100958 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
959 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700960 if (oat_dex_file == nullptr) {
961 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
962 dex_location);
963 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800964 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700965 uint32_t expected_dex_checksum = dex_location_checksum;
966 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
967 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700968 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
969 "found 0x%x", oat_location, expected_dex_checksum,
970 actual_dex_checksum);
971 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800972 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700973 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
974 if (dex_file.get() != nullptr) {
975 return oat_file.release();
976 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700977 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700978 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700979}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700980
Andreas Gampe833a4852014-05-21 18:46:59 -0700981const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
982 int fd, const char* oat_location,
983 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800984 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700985 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -0700986 std::string error_msg;
987 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -0700988 CHECK(!error_msg.empty());
989 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700990 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800991 }
Ian Rogers700a4022014-05-19 16:49:03 -0700992 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, NULL,
Vladimir Marko64e7ac02014-05-01 15:43:47 +0100993 !Runtime::Current()->IsCompiler(),
994 &error_msg));
995 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700996 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
997 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -0700998 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700999 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001000 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001001
1002 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001003}
1004
Alex Light345c4b12014-07-18 14:57:04 -07001005bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1006 const InstructionSet instruction_set) {
1007 Runtime* runtime = Runtime::Current();
1008 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1009 uint32_t image_oat_checksum = 0;
1010 if (instruction_set == kRuntimeISA) {
1011 const ImageHeader& image_header = image_space->GetImageHeader();
1012 image_oat_checksum = image_header.GetOatChecksum();
1013 } else {
1014 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1015 image_space->GetImageLocation().c_str(), instruction_set));
1016 image_oat_checksum = image_header->GetOatChecksum();
1017 }
1018 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1019}
1020
1021bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1022 const InstructionSet instruction_set,
1023 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001024 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001025 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1026
1027 // If the requested instruction set is the same as the current runtime,
1028 // we can use the checksums directly. If it isn't, we'll have to read the
1029 // image header from the image for the right instruction set.
1030 uint32_t image_oat_checksum = 0;
1031 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001032 int32_t image_patch_delta = 0;
1033 if (instruction_set == Runtime::Current()->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001034 const ImageHeader& image_header = image_space->GetImageHeader();
1035 image_oat_checksum = image_header.GetOatChecksum();
1036 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001037 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001038 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001039 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001040 image_space->GetImageLocation().c_str(), instruction_set));
1041 image_oat_checksum = image_header->GetOatChecksum();
1042 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001043 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001044 }
1045 const OatHeader& oat_header = oat_file->GetOatHeader();
Alex Light345c4b12014-07-18 14:57:04 -07001046 bool ret = ((oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum)
1047 && (oat_header.GetImagePatchDelta() == image_patch_delta)
1048 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin));
1049 if (!ret) {
1050 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1051 oat_file->GetLocation().c_str(),
1052 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1053 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1054 oat_file->GetOatHeader().GetImagePatchDelta(),
1055 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1056 }
1057 return ret;
1058}
1059
1060bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1061 const char* dex_location,
1062 uint32_t dex_location_checksum,
1063 const InstructionSet instruction_set,
1064 std::string* error_msg) {
1065 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1066 return false;
1067 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001068
Brian Carlstromf3632832014-05-20 15:36:53 -07001069 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1070 &dex_location_checksum);
Brian Carlstromafe25512012-06-27 17:02:58 -07001071 if (oat_dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001072 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1073 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Brian Carlstromafe25512012-06-27 17:02:58 -07001074 std::vector<const OatFile::OatDexFile*> oat_dex_files = oat_file->GetOatDexFiles();
1075 for (size_t i = 0; i < oat_dex_files.size(); i++) {
1076 const OatFile::OatDexFile* oat_dex_file = oat_dex_files[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001077 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s'",
1078 oat_file->GetLocation().c_str(),
1079 oat_dex_file->GetDexFileLocation().c_str());
Brian Carlstromafe25512012-06-27 17:02:58 -07001080 }
1081 return false;
1082 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001083
Alex Light345c4b12014-07-18 14:57:04 -07001084 if (dex_location_checksum != oat_dex_file->GetDexFileLocationChecksum()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001085 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x) with '%s' (0x%x)",
1086 oat_file->GetLocation().c_str(),
1087 oat_dex_file->GetDexFileLocationChecksum(),
1088 dex_location, dex_location_checksum);
Alex Light345c4b12014-07-18 14:57:04 -07001089 return false;
Brian Carlstromafe25512012-06-27 17:02:58 -07001090 }
Alex Light345c4b12014-07-18 14:57:04 -07001091 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001092}
1093
Alex Lighta59dd802014-07-02 16:28:08 -07001094bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1095 const char* dex_location,
1096 std::string* error_msg) {
1097 CHECK(oat_file != nullptr);
1098 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001099 std::unique_ptr<const DexFile> dex_file;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001100 uint32_t dex_location_checksum;
1101 if (!DexFile::GetChecksum(dex_location, &dex_location_checksum, error_msg)) {
1102 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1103 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1104 // directory.
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001105 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, NULL);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001106 if (oat_dex_file == nullptr) {
1107 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001108 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001109 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001110 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001111 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001112 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001113 } else {
Alex Light345c4b12014-07-18 14:57:04 -07001114 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, dex_location_checksum,
1115 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001116 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001117 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001118 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001119 dex_file.reset(oat_file->GetOatDexFile(dex_location,
1120 &dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001121 }
Alex Lighta59dd802014-07-02 16:28:08 -07001122 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001123}
1124
Andreas Gampe833a4852014-05-21 18:46:59 -07001125const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001126 const char* dex_location,
1127 const uint32_t* const dex_location_checksum,
1128 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001129 std::vector<std::string>* error_msgs,
1130 bool* obsolete_file_cleanup_failed) {
1131 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001132 bool already_opened = false;
1133 std::string dex_location_str(dex_location);
1134 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1135 &already_opened,
1136 obsolete_file_cleanup_failed,
1137 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001138 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001139 if (oat_file.get() == nullptr) {
1140 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1141 dex_location));
1142 return nullptr;
Alex Light0a112bb2014-08-14 14:16:26 -07001143 } else if (oat_file->IsExecutable() &&
1144 !VerifyOatWithDexFile(oat_file.get(), dex_location, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001145 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1146 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001147 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001148 return nullptr;
Alex Light0a112bb2014-08-14 14:16:26 -07001149 } else if (!oat_file->IsExecutable() &&
1150 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1151 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1152 "dex location '%s'. Image checksum incorrect.",
1153 oat_file->GetLocation().c_str(), dex_location));
1154 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001155 } else {
1156 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001157 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001158}
1159
Brian Carlstromae826982011-11-09 01:33:42 -08001160const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001161 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001162 for (size_t i = 0; i < oat_files_.size(); i++) {
1163 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001164 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001165 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001166 return oat_file;
1167 }
1168 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001169 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001170}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001171
Alex Lighta59dd802014-07-02 16:28:08 -07001172const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1173 InstructionSet isa,
1174 bool *already_opened,
1175 bool *obsolete_file_cleanup_failed,
1176 std::vector<std::string>* error_msgs) {
1177 // Find out if we've already opened the file
1178 const OatFile* ret = nullptr;
1179 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1180 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1181 if (ret != nullptr) {
1182 *already_opened = true;
1183 return ret;
1184 }
1185
1186 std::string dalvik_cache;
1187 bool have_android_data = false;
1188 bool have_dalvik_cache = false;
1189 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
1190 &have_android_data, &have_dalvik_cache);
1191 std::string cache_filename;
1192 if (have_dalvik_cache) {
1193 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1194 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1195 if (ret != nullptr) {
1196 *already_opened = true;
1197 return ret;
1198 }
1199 } else {
1200 // If we need to relocate we should just place odex back where it started.
1201 cache_filename = odex_filename;
1202 }
1203
1204 ret = nullptr;
1205
1206 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1207 //
1208 // Now we do the following:
1209 // 1) Try and open the odex version
1210 // 2) If present, checksum-verified & relocated correctly return it
1211 // 3) Close the odex version to free up its address space.
1212 // 4) Try and open the cache version
1213 // 5) If present, checksum-verified & relocated correctly return it
1214 // 6) Close the cache version to free up its address space.
1215 // 7) If we should relocate:
1216 // a) If we have opened and checksum-verified the odex version relocate it to
1217 // 'cache_filename' and return it
1218 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1219 // it. This should not happen often (I think only the run-test's will hit this case).
1220 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1221 // this point.
1222 // 9) Return nullptr
1223
1224 *already_opened = false;
1225 const Runtime* runtime = Runtime::Current();
1226 CHECK(runtime != nullptr);
1227 bool executable = !runtime->IsCompiler();
1228
1229 std::string odex_error_msg;
1230 bool should_patch_system = false;
1231 bool odex_checksum_verified = false;
1232 {
1233 // There is a high probability that these both these oat files map similar/the same address
1234 // spaces so we must scope them like this so they each gets its turn.
1235 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, NULL,
1236 executable, &odex_error_msg));
1237 if (odex_oat_file.get() != nullptr && CheckOatFile(odex_oat_file.get(), isa,
1238 &odex_checksum_verified,
1239 &odex_error_msg)) {
1240 error_msgs->push_back(odex_error_msg);
1241 return odex_oat_file.release();
1242 } else if (odex_checksum_verified) {
1243 // We can just relocate
1244 should_patch_system = true;
1245 odex_error_msg = "Image Patches are incorrect";
1246 }
1247 }
1248
1249
1250 std::string cache_error_msg;
1251 bool should_patch_cache = false;
1252 bool cache_checksum_verified = false;
1253 if (have_dalvik_cache) {
1254 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, NULL,
1255 executable, &cache_error_msg));
1256 if (cache_oat_file.get() != nullptr && CheckOatFile(cache_oat_file.get(), isa,
1257 &cache_checksum_verified,
1258 &cache_error_msg)) {
1259 error_msgs->push_back(cache_error_msg);
1260 return cache_oat_file.release();
1261 } else if (cache_checksum_verified) {
1262 // We can just relocate
1263 should_patch_cache = true;
1264 cache_error_msg = "Image Patches are incorrect";
1265 }
1266 } else if (have_android_data) {
1267 // dalvik_cache does not exist but android data does. This means we should be able to create
1268 // it, so we should try.
1269 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1270 }
1271
1272 ret = nullptr;
1273 std::string error_msg;
1274 if (runtime->CanRelocate()) {
1275 // Run relocation
1276 const std::string& image_location =
1277 Runtime::Current()->GetHeap()->GetImageSpace()->GetImageLocation();
1278 if (odex_checksum_verified && should_patch_system) {
1279 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1280 } else if (cache_checksum_verified && should_patch_cache) {
1281 CHECK(have_dalvik_cache);
1282 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1283 }
1284 }
1285 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1286 // implicitly: were able to fine where the cached version is but we were unable to use it,
1287 // either as a destination for relocation or to open a file. We should delete it if it is
1288 // there.
1289 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1290 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1291 "searching for dex file %s: %s",
1292 cache_filename.c_str(), dex_location.c_str(),
1293 strerror(errno));
1294 error_msgs->push_back(rm_error_msg);
1295 VLOG(class_linker) << rm_error_msg;
1296 // Let the caller know that we couldn't remove the obsolete file.
1297 // This is a good indication that further writes may fail as well.
1298 *obsolete_file_cleanup_failed = true;
1299 }
1300 }
1301 if (ret == nullptr) {
1302 VLOG(class_linker) << error_msg;
1303 error_msgs->push_back(error_msg);
1304 std::string relocation_msg;
1305 if (runtime->CanRelocate()) {
1306 relocation_msg = StringPrintf(" and relocation failed");
1307 }
1308 if (have_dalvik_cache && cache_checksum_verified) {
1309 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1310 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1311 cache_filename.c_str(), cache_error_msg.c_str(),
1312 relocation_msg.c_str());
1313 } else {
1314 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1315 "dalvik_cache availible)%s.", odex_filename.c_str(),
1316 odex_error_msg.c_str(), relocation_msg.c_str());
1317 }
1318 VLOG(class_linker) << error_msg;
1319 error_msgs->push_back(error_msg);
1320 }
1321 return ret;
1322}
1323
Alex Light0a112bb2014-08-14 14:16:26 -07001324const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1325 InstructionSet isa,
1326 std::string* error_msg) {
1327 // We open it non-executable
1328 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, NULL, false, error_msg));
1329 if (output.get() == nullptr) {
1330 return nullptr;
1331 }
1332 if (VerifyOatImageChecksum(output.get(), isa)) {
1333 return output.release();
1334 } else {
1335 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1336 oat_path.c_str());
1337 return nullptr;
1338 }
1339}
1340
Alex Lighta59dd802014-07-02 16:28:08 -07001341const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1342 const std::string& output_oat,
1343 const std::string& image_location,
1344 InstructionSet isa,
1345 std::string* error_msg) {
Alex Light0a112bb2014-08-14 14:16:26 -07001346 if (!Runtime::Current()->IsDex2OatEnabled()) {
1347 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1348 // input_oat but make sure we only do interpretation on it's dex files.
1349 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1350 << "disabled. Attempting to use oat file for interpretation";
1351 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1352 }
Alex Lighta59dd802014-07-02 16:28:08 -07001353 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
1354 std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
1355
1356 std::string isa_arg("--instruction-set=");
1357 isa_arg += GetInstructionSetString(isa);
1358 std::string input_oat_filename_arg("--input-oat-file=");
1359 input_oat_filename_arg += input_oat;
1360 std::string output_oat_filename_arg("--output-oat-file=");
1361 output_oat_filename_arg += output_oat;
1362 std::string patched_image_arg("--patched-image-location=");
1363 patched_image_arg += image_location;
1364
1365 std::vector<std::string> argv;
1366 argv.push_back(patchoat);
1367 argv.push_back(isa_arg);
1368 argv.push_back(input_oat_filename_arg);
1369 argv.push_back(output_oat_filename_arg);
1370 argv.push_back(patched_image_arg);
1371
1372 std::string command_line(Join(argv, ' '));
1373 LOG(INFO) << "Relocate Oat File: " << command_line;
1374 bool success = Exec(argv, error_msg);
1375 if (success) {
1376 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, NULL,
1377 !Runtime::Current()->IsCompiler(), error_msg));
1378 bool checksum_verified = false;
1379 if (output.get() != nullptr && CheckOatFile(output.get(), isa, &checksum_verified, error_msg)) {
1380 return output.release();
1381 } else if (output.get() != nullptr) {
1382 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1383 "but output file '%s' failed verifcation: %s",
1384 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1385 } else {
1386 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1387 "but was unable to open output file '%s': %s",
1388 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1389 }
Alex Light0a112bb2014-08-14 14:16:26 -07001390 } else if (!Runtime::Current()->IsCompiler()) {
1391 // patchoat failed which means we probably don't have enough room to place the output oat file,
1392 // instead of failing we should just run the interpreter from the dex files in the input oat.
1393 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1394 << "for interpretation. patchoat failure was: " << *error_msg;
1395 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001396 } else {
1397 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1398 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1399 error_msg->c_str());
1400 }
1401 return nullptr;
1402}
1403
1404int32_t ClassLinker::GetRequiredDelta(const OatFile* oat_file, InstructionSet isa) {
1405 Runtime* runtime = Runtime::Current();
1406 int32_t real_patch_delta;
1407 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1408 if (isa == Runtime::Current()->GetInstructionSet()) {
1409 const ImageHeader& image_header = image_space->GetImageHeader();
1410 real_patch_delta = image_header.GetPatchDelta();
1411 } else {
1412 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1413 image_space->GetImageLocation().c_str(), isa));
1414 real_patch_delta = image_header->GetPatchDelta();
1415 }
1416 const OatHeader& oat_header = oat_file->GetOatHeader();
1417 return real_patch_delta - oat_header.GetImagePatchDelta();
1418}
1419
1420bool ClassLinker::CheckOatFile(const OatFile* oat_file, InstructionSet isa,
1421 bool* checksum_verified,
1422 std::string* error_msg) {
1423 std::string compound_msg("Oat file failed to verify: ");
1424 Runtime* runtime = Runtime::Current();
1425 uint32_t real_image_checksum;
1426 void* real_image_oat_offset;
1427 int32_t real_patch_delta;
1428 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1429 if (isa == Runtime::Current()->GetInstructionSet()) {
1430 const ImageHeader& image_header = image_space->GetImageHeader();
1431 real_image_checksum = image_header.GetOatChecksum();
1432 real_image_oat_offset = image_header.GetOatDataBegin();
1433 real_patch_delta = image_header.GetPatchDelta();
1434 } else {
1435 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1436 image_space->GetImageLocation().c_str(), isa));
1437 real_image_checksum = image_header->GetOatChecksum();
1438 real_image_oat_offset = image_header->GetOatDataBegin();
1439 real_patch_delta = image_header->GetPatchDelta();
1440 }
1441
1442 const OatHeader& oat_header = oat_file->GetOatHeader();
1443
1444 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1445 *checksum_verified = oat_image_checksum == real_image_checksum;
1446 if (!*checksum_verified) {
1447 compound_msg += StringPrintf(" Oat Image Checksum Incorrect (expected 0x%x, recieved 0x%x)",
1448 real_image_checksum, oat_image_checksum);
1449 }
1450
1451 void* oat_image_oat_offset =
1452 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1453 bool offset_verified = oat_image_oat_offset == real_image_oat_offset;
1454 if (!offset_verified) {
1455 compound_msg += StringPrintf(" Oat Image oat offset incorrect (expected 0x%p, recieved 0x%p)",
1456 real_image_oat_offset, oat_image_oat_offset);
1457 }
1458
1459 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1460 bool patch_delta_verified = oat_patch_delta == real_patch_delta;
1461 if (!patch_delta_verified) {
1462 compound_msg += StringPrintf(" Oat image patch delta incorrect (expected 0x%x, recieved 0x%x)",
1463 real_patch_delta, oat_patch_delta);
1464 }
1465
1466 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
1467 if (ret) {
1468 *error_msg = compound_msg;
1469 }
1470 return ret;
1471}
1472
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001473const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1474 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001475 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001476 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001477 return oat_file;
1478 }
1479
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001480 oat_file = OatFile::Open(oat_location, oat_location, NULL, !Runtime::Current()->IsCompiler(),
1481 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001482 if (oat_file == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -08001483 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001484 }
1485 return oat_file;
1486}
1487
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001488static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
Ian Rogers848871b2013-08-05 10:56:33 -07001489 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001490 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1491
Ian Rogers848871b2013-08-05 10:56:33 -07001492 DCHECK(obj != NULL);
1493 DCHECK(class_linker != NULL);
1494
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001495 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001496 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001497 if (!method->IsNative()) {
1498 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
1499 if (method != Runtime::Current()->GetResolutionMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001500 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1501 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers848871b2013-08-05 10:56:33 -07001502 }
1503 }
1504 }
1505}
1506
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001507void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001508 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001509 CHECK(!init_done_);
1510
Mathieu Chartier590fee92013-09-13 13:46:47 -07001511 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001512 gc::Heap* heap = Runtime::Current()->GetHeap();
1513 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001514 dex_cache_image_class_lookup_required_ = true;
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001515 CHECK(space != NULL);
1516 OatFile& oat_file = GetImageOatFile(space);
1517 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1518 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001519 const char* image_file_location = oat_file.GetOatHeader().
1520 GetStoreValueByKey(OatHeader::kImageLocationKey);
1521 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001522 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1523 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001524 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1525 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001526 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001527 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001528 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1529 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1530 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001531
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001532 StackHandleScope<1> hs(self);
1533 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1534 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1535 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001536 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001537
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001538 // Special case of setting up the String class early so that we can test arbitrary objects
1539 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001540 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001541
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001542 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001543 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001544 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001545 StackHandleScope<1> hs(self);
1546 Handle<mirror::DexCache> dex_cache(hs.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001547 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001548 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1549 nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001550 CHECK(oat_dex_file != NULL) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001551 std::string error_msg;
1552 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001553 if (dex_file == NULL) {
1554 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001555 << " from within oat file " << oat_file.GetLocation()
1556 << " error '" << error_msg << "'";
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001557 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001558
1559 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1560
1561 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001562 }
1563
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001564 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1565 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001566 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001567
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001568 // Set entry point to interpreter if in InterpretOnly mode.
1569 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001570 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001571 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001572 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001573
1574 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001575 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001576 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001577
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001578 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001579 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
1580 DCHECK(array_iftable_.Read() == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001581 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001582 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001583 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001584 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1585 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1586 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1587 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1588 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1589 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1590 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1591 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1592 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1593 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001594
Ian Rogers98379392014-02-24 16:53:16 -08001595 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001596
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001597 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001598}
1599
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001600void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1601 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1602 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001603 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1604 it.second.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001605 }
1606 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1607 for (auto& pair : new_class_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001608 mirror::Class* old_ref = pair.second.Read<kWithoutReadBarrier>();
1609 pair.second.VisitRoot(callback, arg, 0, kRootStickyClass);
1610 mirror::Class* new_ref = pair.second.Read<kWithoutReadBarrier>();
1611 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001612 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1613 // corresponding object. This is slow, but luckily for us, this may only happen with a
1614 // concurrent moving GC.
1615 for (auto it = class_table_.lower_bound(pair.first), end = class_table_.end();
1616 it != end && it->first == pair.first; ++it) {
1617 // If the class stored matches the old class, update it to the new value.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001618 if (old_ref == it->second.Read<kWithoutReadBarrier>()) {
1619 it->second = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001620 }
1621 }
1622 }
1623 }
1624 }
1625 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1626 new_class_roots_.clear();
1627 }
1628 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1629 log_new_class_table_roots_ = true;
1630 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1631 log_new_class_table_roots_ = false;
1632 }
1633 // We deliberately ignore the class roots in the image since we
1634 // handle image roots by using the MS/CMS rescanning of dirty cards.
1635}
1636
Brian Carlstroma663ea52011-08-19 23:33:41 -07001637// Keep in sync with InitCallback. Anything we visit, we need to
1638// reinit references to when reinitializing a ClassLinker from a
1639// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001640void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001641 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001642 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001643 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001644 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001645 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001646 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1647 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001648 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001649 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1650 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001651 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001652 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001653 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001654 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1655 new_dex_cache_roots_.clear();
1656 }
1657 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1658 log_new_dex_caches_roots_ = true;
1659 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1660 log_new_dex_caches_roots_ = false;
1661 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001662 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001663 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001664 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1665 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001666 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001667 if (!find_array_class_cache_[i].IsNull()) {
1668 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001669 }
1670 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001671}
1672
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001673void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1674 if (dex_cache_image_class_lookup_required_) {
1675 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001676 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001677 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001678 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1679 mirror::Class* c = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07001680 if (!visitor(c, arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001681 return;
1682 }
1683 }
1684}
1685
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001686static bool GetClassesVisitor(mirror::Class* c, void* arg) {
1687 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001688 classes->insert(c);
1689 return true;
1690}
1691
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001692void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001693 std::set<mirror::Class*> classes;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001694 VisitClasses(GetClassesVisitor, &classes);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001695 for (mirror::Class* klass : classes) {
1696 if (!visitor(klass, arg)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001697 return;
1698 }
1699 }
1700}
1701
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001702ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001703 mirror::Class::ResetClass();
1704 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001705 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001706 mirror::ArtField::ResetClass();
1707 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001708 mirror::BooleanArray::ResetArrayClass();
1709 mirror::ByteArray::ResetArrayClass();
1710 mirror::CharArray::ResetArrayClass();
1711 mirror::DoubleArray::ResetArrayClass();
1712 mirror::FloatArray::ResetArrayClass();
1713 mirror::IntArray::ResetArrayClass();
1714 mirror::LongArray::ResetArrayClass();
1715 mirror::ShortArray::ResetArrayClass();
1716 mirror::Throwable::ResetClass();
1717 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001718 STLDeleteElements(&boot_class_path_);
1719 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001720}
1721
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001722mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001723 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001724 StackHandleScope<16> hs(self);
1725 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1726 Handle<mirror::DexCache> dex_cache(
1727 hs.NewHandle(down_cast<mirror::DexCache*>(
1728 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1729 VoidFunctor()))));
1730 if (dex_cache.Get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001731 return NULL;
1732 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001733 Handle<mirror::String>
1734 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
1735 if (location.Get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001736 return NULL;
1737 }
Ian Rogers700a4022014-05-19 16:49:03 -07001738 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001739 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
1740 if (strings.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001741 return NULL;
1742 }
Ian Rogers700a4022014-05-19 16:49:03 -07001743 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001744 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
1745 if (types.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001746 return NULL;
1747 }
Ian Rogers700a4022014-05-19 16:49:03 -07001748 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001749 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
1750 if (methods.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001751 return NULL;
1752 }
Ian Rogers700a4022014-05-19 16:49:03 -07001753 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001754 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
1755 if (fields.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001756 return NULL;
1757 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001758 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1759 fields.Get());
1760 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001761}
1762
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001763mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001764 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001765 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001766 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001767 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001768 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001769 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1770 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001771 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001772 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001773 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001774 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001775 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001776}
1777
Ian Rogers6fac4472014-02-25 17:01:10 -08001778mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001779 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001780}
1781
Brian Carlstromea46f952013-07-30 01:26:50 -07001782mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001783 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001784 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001785}
1786
Brian Carlstromea46f952013-07-30 01:26:50 -07001787mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001788 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001789 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001790}
1791
Mathieu Chartier590fee92013-09-13 13:46:47 -07001792mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1793 Thread* self, size_t length) {
1794 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1795 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001796}
1797
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001798mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1799 mirror::Class* klass) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001800 DCHECK(klass != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001801
1802 // For temporary classes we must wait for them to be retired.
1803 if (init_done_ && klass->IsTemp()) {
1804 CHECK(!klass->IsResolved());
1805 if (klass->IsErroneous()) {
1806 ThrowEarlierClassFailure(klass);
1807 return nullptr;
1808 }
1809 StackHandleScope<1> hs(self);
1810 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1811 ObjectLock<mirror::Class> lock(self, h_class);
1812 // Loop and wait for the resolving thread to retire this class.
1813 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1814 lock.WaitIgnoringInterrupts();
1815 }
1816 if (h_class->IsErroneous()) {
1817 ThrowEarlierClassFailure(h_class.Get());
1818 return nullptr;
1819 }
1820 CHECK(h_class->IsRetired());
1821 // Get the updated class from class table.
1822 klass = LookupClass(descriptor, h_class.Get()->GetClassLoader());
1823 }
1824
Brian Carlstromaded5f72011-10-07 17:15:04 -07001825 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001826 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001827 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001828 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
1829 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001830 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001831 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
1832 ThrowClassCircularityError(h_class.Get());
1833 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001834 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001835 }
1836 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001837 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08001838 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001839 }
1840 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001841
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001842 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001843 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001844 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001845 }
1846 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001847 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08001848 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001849 return klass;
1850}
1851
Ian Rogers98379392014-02-24 16:53:16 -08001852mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07001853 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001854 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08001855 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001856 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001857 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001858 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1859 // for primitive classes that aren't backed by dex files.
1860 return FindPrimitiveClass(descriptor[0]);
1861 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001862 // Find the class in the loaded classes table.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001863 mirror::Class* klass = LookupClass(descriptor, class_loader.Get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001864 if (klass != NULL) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001865 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001866 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001867 // Class is not yet loaded.
1868 if (descriptor[0] == '[') {
Ian Rogers98379392014-02-24 16:53:16 -08001869 return CreateArrayClass(self, descriptor, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001870 } else if (class_loader.Get() == nullptr) {
Jesse Wilson47daf872011-11-23 11:42:45 -05001871 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1872 if (pair.second != NULL) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001873 StackHandleScope<1> hs(self);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07001874 return DefineClass(descriptor, NullHandle<mirror::ClassLoader>(), *pair.first, *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05001875 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001876 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogersbe7149f2013-08-20 09:29:39 -07001877 // First try the boot class path, we check the descriptor first to avoid an unnecessary
1878 // throw of a NoClassDefFoundError.
1879 if (IsInBootClassPath(descriptor)) {
Ian Rogers98379392014-02-24 16:53:16 -08001880 mirror::Class* system_class = FindSystemClass(self, descriptor);
Ian Rogersbe7149f2013-08-20 09:29:39 -07001881 CHECK(system_class != NULL);
Jesse Wilson47daf872011-11-23 11:42:45 -05001882 return system_class;
1883 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07001884 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001885 const std::vector<const DexFile*>* class_path;
1886 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07001887 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001888 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001889 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001890 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
1891 }
1892
1893 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, *class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001894 if (pair.second != NULL) {
1895 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001896 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001897
1898 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001899 ScopedObjectAccessUnchecked soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001900 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001901 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08001902 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001903 ScopedLocalRef<jobject> result(soa.Env(), NULL);
Ian Rogers365c1022012-06-22 15:05:28 -07001904 {
1905 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001906 ScopedLocalRef<jobject> class_name_object(soa.Env(),
1907 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers365c1022012-06-22 15:05:28 -07001908 if (class_name_object.get() == NULL) {
1909 return NULL;
1910 }
1911 CHECK(class_loader_object.get() != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001912 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
1913 WellKnownClasses::java_lang_ClassLoader_loadClass,
1914 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05001915 }
Ian Rogers98379392014-02-24 16:53:16 -08001916 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001917 // If the ClassLoader threw, pass that exception up.
1918 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001919 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001920 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers62d6c772013-02-27 08:32:07 -08001921 ThrowNullPointerException(NULL, StringPrintf("ClassLoader.loadClass returned null for %s",
1922 class_name_string.c_str()).c_str());
Ian Rogerscab01012012-01-10 17:35:46 -08001923 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001924 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001925 // success, return mirror::Class*
1926 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001927 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001928 }
1929
Elliott Hughes82914b62012-04-09 15:56:29 -07001930 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001931 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001932}
1933
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001934mirror::Class* ClassLinker::DefineClass(const char* descriptor,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07001935 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001936 const DexFile& dex_file,
1937 const DexFile::ClassDef& dex_class_def) {
Ian Rogers1f539342012-10-03 21:09:42 -07001938 Thread* self = Thread::Current();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001939 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001940 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001941 bool should_allocate = false;
1942
Brian Carlstromaded5f72011-10-07 17:15:04 -07001943 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001944 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001945 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001946 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001947 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001948 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001949 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001950 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001951 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07001952 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
1953 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001954 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001955 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001956 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001957 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001958 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001959 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001960 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001961 should_allocate = true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001962 }
1963 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001964 should_allocate = true;
1965 }
1966
1967 if (should_allocate) {
1968 // Allocate a class with the status of not ready.
1969 // Interface object should get the right size here. Regular class will
1970 // figure out the right size later and be replaced with one of the right
1971 // size when the class becomes resolved.
1972 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001973 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001974 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001975 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07001976 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001977 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001978 klass->SetDexCache(FindDexCache(dex_file));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001979 LoadClass(dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001980 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07001981 if (self->IsExceptionPending()) {
1982 // An exception occured during load, set status to erroneous while holding klass' lock in case
1983 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001984 if (!klass->IsErroneous()) {
1985 klass->SetStatus(mirror::Class::kStatusError, self);
1986 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001987 return nullptr;
1988 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001989 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001990
Mathieu Chartier590fee92013-09-13 13:46:47 -07001991 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001992 mirror::Class* existing = InsertClass(descriptor, klass.Get(), Hash(descriptor));
Ian Rogersc114b5f2014-07-21 08:55:01 -07001993 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001994 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
1995 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001996 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001997 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001998
Brian Carlstromaded5f72011-10-07 17:15:04 -07001999 // Finish loading (if necessary) by finding parents
2000 CHECK(!klass->IsLoaded());
2001 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2002 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002003 if (!klass->IsErroneous()) {
2004 klass->SetStatus(mirror::Class::kStatusError, self);
2005 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002006 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002007 }
2008 CHECK(klass->IsLoaded());
2009 // Link the class (if necessary)
2010 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002011 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002012 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002013
2014 mirror::Class* new_class = nullptr;
2015 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002016 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002017 if (!klass->IsErroneous()) {
2018 klass->SetStatus(mirror::Class::kStatusError, self);
2019 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002020 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002021 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002022 CHECK(new_class != nullptr) << descriptor;
2023 CHECK(new_class->IsResolved()) << descriptor;
2024
2025 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002026
2027 /*
2028 * We send CLASS_PREPARE events to the debugger from here. The
2029 * definition of "preparation" is creating the static fields for a
2030 * class and initializing them to the standard default values, but not
2031 * executing any code (that comes later, during "initialization").
2032 *
2033 * We did the static preparation in LinkClass.
2034 *
2035 * The class has been prepared and resolved but possibly not yet verified
2036 * at this point.
2037 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002038 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002039
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002040 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002041}
2042
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002043uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2044 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002045 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002046 size_t num_ref = 0;
2047 size_t num_32 = 0;
2048 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002049 if (class_data != NULL) {
2050 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2051 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002052 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002053 char c = descriptor[0];
2054 if (c == 'L' || c == '[') {
2055 num_ref++;
2056 } else if (c == 'J' || c == 'D') {
2057 num_64++;
2058 } else {
2059 num_32++;
2060 }
2061 }
2062 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002063 return mirror::Class::ComputeClassSize(false, 0, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002064}
2065
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002066bool ClassLinker::FindOatClass(const DexFile& dex_file,
2067 uint16_t class_def_idx,
2068 OatFile::OatClass* oat_class) {
2069 DCHECK(oat_class != nullptr);
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002070 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Ian Rogers19846512012-02-24 11:42:47 -08002071 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002072 if (oat_file == nullptr) {
2073 return false;
2074 }
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07002075 uint dex_location_checksum = dex_file.GetLocationChecksum();
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002076 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation().c_str(),
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07002077 &dex_location_checksum);
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002078 CHECK(oat_dex_file != NULL) << dex_file.GetLocation();
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002079 *oat_class = oat_dex_file->GetOatClass(class_def_idx);
2080 return true;
Ian Rogers19846512012-02-24 11:42:47 -08002081}
2082
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002083static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2084 uint32_t method_idx) {
2085 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
2086 const byte* class_data = dex_file.GetClassData(class_def);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002087 CHECK(class_data != NULL);
2088 ClassDataItemIterator it(dex_file, class_data);
2089 // Skip fields
2090 while (it.HasNextStaticField()) {
2091 it.Next();
2092 }
2093 while (it.HasNextInstanceField()) {
2094 it.Next();
2095 }
2096 // Process methods
2097 size_t class_def_method_index = 0;
2098 while (it.HasNextDirectMethod()) {
2099 if (it.GetMemberIndex() == method_idx) {
2100 return class_def_method_index;
2101 }
2102 class_def_method_index++;
2103 it.Next();
2104 }
2105 while (it.HasNextVirtualMethod()) {
2106 if (it.GetMemberIndex() == method_idx) {
2107 return class_def_method_index;
2108 }
2109 class_def_method_index++;
2110 it.Next();
2111 }
2112 DCHECK(!it.HasNext());
2113 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2114 return 0;
2115}
2116
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002117bool ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, OatFile::OatMethod* oat_method) {
2118 DCHECK(oat_method != nullptr);
Ian Rogers19846512012-02-24 11:42:47 -08002119 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002120 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002121 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002122 size_t oat_method_index;
2123 if (method->IsStatic() || method->IsDirect()) {
2124 // Simple case where the oat method index was stashed at load time.
2125 oat_method_index = method->GetMethodIndex();
2126 } else {
2127 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2128 // by search for its position in the declared virtual methods.
2129 oat_method_index = declaring_class->NumDirectMethods();
2130 size_t end = declaring_class->NumVirtualMethods();
2131 bool found = false;
2132 for (size_t i = 0; i < end; i++) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08002133 if (declaring_class->GetVirtualMethod(i) == method) {
2134 found = true;
2135 break;
2136 }
Ian Rogersf320b632012-03-13 18:47:47 -07002137 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002138 }
2139 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method);
2140 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002141 DCHECK_EQ(oat_method_index,
2142 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002143 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002144 method->GetDexMethodIndex()));
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002145 OatFile::OatClass oat_class;
2146 if (!FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2147 declaring_class->GetDexClassDefIndex(),
2148 &oat_class)) {
2149 return false;
2150 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002151
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002152 *oat_method = oat_class.GetOatMethod(oat_method_index);
2153 return true;
TDYa12785321912012-04-01 15:24:56 -07002154}
2155
2156// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002157const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002158 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002159 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002160 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002161 }
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002162 OatFile::OatMethod oat_method;
2163 const void* result = nullptr;
2164 if (FindOatMethodFor(method, &oat_method)) {
2165 result = oat_method.GetQuickCode();
2166 }
2167
Ian Rogersef7d42f2014-01-06 12:55:46 -08002168 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002169 if (method->IsNative()) {
2170 // No code and native? Use generic trampoline.
2171 result = GetQuickGenericJniTrampoline();
2172 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002173 // No code? Do we expect portable code?
2174 result = GetQuickToPortableBridge();
2175 } else {
2176 // No code? You must mean to go into the interpreter.
2177 result = GetQuickToInterpreterBridge();
2178 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002179 }
2180 return result;
TDYa12785321912012-04-01 15:24:56 -07002181}
2182
Ian Rogersef7d42f2014-01-06 12:55:46 -08002183const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2184 bool* have_portable_code) {
2185 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2186 *have_portable_code = false;
2187 if (method->IsProxyMethod()) {
2188 return GetPortableProxyInvokeHandler();
2189 }
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002190 OatFile::OatMethod oat_method;
2191 const void* result = nullptr;
2192 const void* quick_code = nullptr;
2193 if (FindOatMethodFor(method, &oat_method)) {
2194 result = oat_method.GetPortableCode();
2195 quick_code = oat_method.GetQuickCode();
2196 }
2197
Ian Rogersef7d42f2014-01-06 12:55:46 -08002198 if (result == nullptr) {
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002199 if (quick_code == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002200 // No code? You must mean to go into the interpreter.
2201 result = GetPortableToInterpreterBridge();
2202 } else {
2203 // No code? But there's quick code, so use a bridge.
2204 result = GetPortableToQuickBridge();
2205 }
2206 } else {
2207 *have_portable_code = true;
2208 }
2209 return result;
2210}
2211
2212const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2213 uint32_t method_idx) {
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002214 OatFile::OatClass oat_class;
2215 if (!FindOatClass(dex_file, class_def_idx, &oat_class)) {
2216 return nullptr;
2217 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002218 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002219 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002220}
2221
2222const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2223 uint32_t method_idx) {
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002224 OatFile::OatClass oat_class;
2225 if (!FindOatClass(dex_file, class_def_idx, &oat_class)) {
2226 return nullptr;
2227 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002228 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002229 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002230}
2231
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002232// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002233static bool NeedsInterpreter(
2234 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2235 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002236 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002237 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002238 // May return true for native code, in the case of generic JNI
2239 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002240 return true;
2241 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002242#ifdef ART_SEA_IR_MODE
2243 ScopedObjectAccess soa(Thread::Current());
2244 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2245 LOG(INFO) << "Found " << PrettyMethod(method);
2246 return false;
2247 }
2248#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002249 // If interpreter mode is enabled, every method (except native and proxy) must
2250 // be run with interpreter.
2251 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2252 !method->IsNative() && !method->IsProxyMethod();
2253}
2254
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002255void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002256 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002257 if (klass->NumDirectMethods() == 0) {
2258 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002259 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002260 Runtime* runtime = Runtime::Current();
2261 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Ian Rogers1c829822013-09-30 18:18:50 -07002262 return; // OAT file unavailable.
Ian Rogers19846512012-02-24 11:42:47 -08002263 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07002264 const DexFile& dex_file = klass->GetDexFile();
2265 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002266 CHECK(dex_class_def != nullptr);
2267 const byte* class_data = dex_file.GetClassData(*dex_class_def);
2268 // There should always be class data if there were direct methods.
2269 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002270 ClassDataItemIterator it(dex_file, class_data);
2271 // Skip fields
2272 while (it.HasNextStaticField()) {
2273 it.Next();
2274 }
2275 while (it.HasNextInstanceField()) {
2276 it.Next();
2277 }
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002278 OatFile::OatClass oat_class;
2279 bool has_oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(), &oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002280 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002281 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002282 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002283 if (!method->IsStatic()) {
2284 // Only update static methods.
2285 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002286 }
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002287 const void* portable_code = nullptr;
2288 const void* quick_code = nullptr;
2289 if (has_oat_class) {
2290 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2291 portable_code = oat_method.GetPortableCode();
2292 quick_code = oat_method.GetQuickCode();
2293 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002294 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2295 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002296 if (enter_interpreter) {
2297 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002298 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002299 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
2300 quick_code = GetQuickGenericJniTrampoline();
Ian Rogers1a570662014-03-12 01:02:21 -07002301 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002302 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002303 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002304 quick_code = GetQuickToInterpreterBridge();
2305 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002306 } else {
2307 if (portable_code == nullptr) {
2308 portable_code = GetPortableToQuickBridge();
2309 } else {
2310 have_portable_code = true;
2311 }
2312 if (quick_code == nullptr) {
2313 quick_code = GetQuickToPortableBridge();
2314 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002315 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002316 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2317 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002318 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002319 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002320}
2321
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002322void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method, const OatFile::OatClass* oat_class,
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002323 const DexFile& dex_file, uint32_t dex_method_index,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002324 uint32_t method_index) {
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002325 if (Runtime::Current()->IsCompiler()) {
2326 // The following code only applies to a non-compiler runtime.
2327 return;
2328 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002329 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002330 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2331 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002332 if (oat_class != nullptr) {
2333 // Every kind of method should at least get an invoke stub from the oat_method.
2334 // non-abstract methods also get their code pointers.
2335 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
2336 oat_method.LinkMethod(method.Get());
2337 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002338
Jeff Hao16743632013-05-08 10:59:04 -07002339 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002340 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002341 method->GetEntryPointFromQuickCompiledCode(),
2342 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002343 if (enter_interpreter && !method->IsNative()) {
Ian Rogers848871b2013-08-05 10:56:33 -07002344 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002345 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002346 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002347 }
2348
Brian Carlstrom92827a52011-10-10 15:50:01 -07002349 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002350 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2351 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002352 return;
2353 }
Ian Rogers19846512012-02-24 11:42:47 -08002354
Ian Rogersef7d42f2014-01-06 12:55:46 -08002355 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002356 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002357 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002358 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2359 // after initializing class (see ClassLinker::InitializeClass method).
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002360 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionTrampoline());
2361 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionTrampoline());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002362 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002363 if (!method->IsNative()) {
2364 // Set entry point from compiled code if there's no code or in interpreter only mode.
2365 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2366 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2367 } else {
2368 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniTrampoline());
2369 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2370 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002371 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2372 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2373 have_portable_code = true;
2374 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2375 } else {
2376 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2377 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002378 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002379
Ian Rogers62d6c772013-02-27 08:32:07 -08002380 if (method->IsNative()) {
2381 // Unregistering restores the dlsym lookup stub.
2382 method->UnregisterNative(Thread::Current());
Andreas Gampe90546832014-03-12 18:07:19 -07002383
2384 if (enter_interpreter) {
2385 // We have a native method here without code. Then it should have either the GenericJni
2386 // trampoline as entrypoint (non-static), or the Resolution trampoline (static).
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002387 DCHECK(method->GetEntryPointFromQuickCompiledCode() == GetQuickResolutionTrampoline()
Andreas Gampe9a6a99a2014-03-14 07:52:20 -07002388 || method->GetEntryPointFromQuickCompiledCode() == GetQuickGenericJniTrampoline());
Andreas Gampe90546832014-03-12 18:07:19 -07002389 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002390 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002391
Ian Rogers62d6c772013-02-27 08:32:07 -08002392 // Allow instrumentation its chance to hijack code.
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002393 Runtime* runtime = Runtime::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002394 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002395 method->GetEntryPointFromQuickCompiledCode(),
2396 method->GetEntryPointFromPortableCompiledCode(),
2397 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002398}
2399
Brian Carlstromf615a612011-07-23 12:50:34 -07002400void ClassLinker::LoadClass(const DexFile& dex_file,
2401 const DexFile::ClassDef& dex_class_def,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002402 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002403 mirror::ClassLoader* class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002404 CHECK(klass.Get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002405 CHECK(klass->GetDexCache() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002406 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002407 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002408 CHECK(descriptor != NULL);
2409
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002410 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002411 if (kUseBakerOrBrooksReadBarrier) {
2412 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002413 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002414 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07002415 // Make sure that none of our runtime-only flags are set.
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002416 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002417 klass->SetAccessFlags(access_flags);
2418 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002419 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002420 klass->SetStatus(mirror::Class::kStatusIdx, NULL);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002421
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002422 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002423 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002424
Ian Rogers0571d352011-11-03 19:51:38 -07002425 const byte* class_data = dex_file.GetClassData(dex_class_def);
2426 if (class_data == NULL) {
2427 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002428 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002429
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002430 OatFile::OatClass oat_class;
2431 if (Runtime::Current()->IsStarted()
2432 && !Runtime::Current()->UseCompileTimeClassPath()
2433 && FindOatClass(dex_file, klass->GetDexClassDefIndex(), &oat_class)) {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002434 LoadClassMembers(dex_file, class_data, klass, class_loader, &oat_class);
2435 } else {
2436 LoadClassMembers(dex_file, class_data, klass, class_loader, nullptr);
2437 }
2438}
2439
2440void ClassLinker::LoadClassMembers(const DexFile& dex_file,
2441 const byte* class_data,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002442 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002443 mirror::ClassLoader* class_loader,
2444 const OatFile::OatClass* oat_class) {
2445 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002446 ClassDataItemIterator it(dex_file, class_data);
Ian Rogers50b35e22012-10-04 10:09:15 -07002447 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07002448 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002449 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
2450 if (UNLIKELY(statics == NULL)) {
2451 CHECK(self->IsExceptionPending()); // OOME.
2452 return;
2453 }
2454 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002455 }
2456 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002457 mirror::ObjectArray<mirror::ArtField>* fields =
2458 AllocArtFieldArray(self, it.NumInstanceFields());
2459 if (UNLIKELY(fields == NULL)) {
2460 CHECK(self->IsExceptionPending()); // OOME.
2461 return;
2462 }
2463 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002464 }
2465 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002466 StackHandleScope<1> hs(self);
2467 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
2468 if (UNLIKELY(sfield.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002469 CHECK(self->IsExceptionPending()); // OOME.
2470 return;
2471 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002472 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002473 LoadField(dex_file, it, klass, sfield);
2474 }
2475 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002476 StackHandleScope<1> hs(self);
2477 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
2478 if (UNLIKELY(ifield.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002479 CHECK(self->IsExceptionPending()); // OOME.
2480 return;
2481 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002482 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002483 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002484 }
2485
Ian Rogers0571d352011-11-03 19:51:38 -07002486 // Load methods.
2487 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002488 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002489 mirror::ObjectArray<mirror::ArtMethod>* directs =
2490 AllocArtMethodArray(self, it.NumDirectMethods());
2491 if (UNLIKELY(directs == NULL)) {
2492 CHECK(self->IsExceptionPending()); // OOME.
2493 return;
2494 }
2495 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002496 }
Ian Rogers0571d352011-11-03 19:51:38 -07002497 if (it.NumVirtualMethods() != 0) {
2498 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002499 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2500 AllocArtMethodArray(self, it.NumVirtualMethods());
2501 if (UNLIKELY(virtuals == NULL)) {
2502 CHECK(self->IsExceptionPending()); // OOME.
2503 return;
2504 }
2505 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002506 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002507 size_t class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002508 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002509 StackHandleScope<1> hs(self);
2510 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
2511 if (UNLIKELY(method.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002512 CHECK(self->IsExceptionPending()); // OOME.
2513 return;
2514 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002515 klass->SetDirectMethod(i, method.Get());
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002516 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002517 method->SetMethodIndex(class_def_method_index);
2518 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002519 }
2520 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002521 StackHandleScope<1> hs(self);
2522 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
2523 if (UNLIKELY(method.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002524 CHECK(self->IsExceptionPending()); // OOME.
2525 return;
2526 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002527 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002528 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002529 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002530 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002531 }
2532 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002533}
2534
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002535void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002536 Handle<mirror::Class> klass, Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002537 uint32_t field_idx = it.GetMemberIndex();
2538 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002539 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002540 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002541}
2542
Brian Carlstromea46f952013-07-30 01:26:50 -07002543mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002544 const ClassDataItemIterator& it,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002545 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002546 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002547 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002548 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002549
Brian Carlstromea46f952013-07-30 01:26:50 -07002550 mirror::ArtMethod* dst = AllocArtMethod(self);
Ian Rogersa436fde2013-08-27 23:34:06 -07002551 if (UNLIKELY(dst == NULL)) {
2552 CHECK(self->IsExceptionPending()); // OOME.
2553 return NULL;
2554 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002555 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002556
Ian Rogers50b35e22012-10-04 10:09:15 -07002557 const char* old_cause = self->StartAssertNoThreadSuspension("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002558 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002559 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002560 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002561
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002562 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
Ian Rogers19846512012-02-24 11:42:47 -08002563 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002564 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002565
Ian Rogers241b5de2013-10-09 17:58:57 -07002566 uint32_t access_flags = it.GetMemberAccessFlags();
2567
Ian Rogersdfb325e2013-10-30 01:00:44 -07002568 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002569 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002570 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2571 // Void return type.
Ian Rogerscb6b0f32014-08-12 02:30:58 -07002572 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002573 klass->SetFinalizable();
2574 } else {
Ian Rogerscb6b0f32014-08-12 02:30:58 -07002575 std::string temp;
2576 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002577 // The Enum class declares a "final" finalize() method to prevent subclasses from
2578 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2579 // subclasses, so we exclude it here.
2580 // We also want to avoid setting the flag on Object, where we know that finalize() is
2581 // empty.
Ian Rogerscb6b0f32014-08-12 02:30:58 -07002582 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2583 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002584 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002585 }
2586 }
2587 }
2588 } else if (method_name[0] == '<') {
2589 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002590 bool is_init = (strcmp("<init>", method_name) == 0);
2591 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002592 if (UNLIKELY(!is_init && !is_clinit)) {
2593 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2594 } else {
2595 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2596 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002597 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002598 access_flags |= kAccConstructor;
2599 }
2600 }
2601 }
2602 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002603
Ian Rogers50b35e22012-10-04 10:09:15 -07002604 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002605 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002606}
2607
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002608void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002609 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002610 StackHandleScope<1> hs(self);
2611 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
2612 CHECK(dex_cache.Get() != NULL) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002613 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002614}
2615
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002616void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002617 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002618 CHECK(dex_cache.Get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002619 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002620 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002621}
2622
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002623bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002624 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002625 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002626 mirror::DexCache* dex_cache = GetDexCache(i);
2627 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002628 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002629 }
2630 }
2631 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002632}
2633
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002634bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002635 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002636 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002637}
2638
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002639void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002640 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002641 dex_lock_.AssertExclusiveHeld(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002642 CHECK(dex_cache.Get() != NULL) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002643 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2644 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002645 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002646 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002647 if (log_new_dex_caches_roots_) {
2648 // TODO: This is not safe if we can remove dex caches.
2649 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2650 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002651}
2652
Brian Carlstromaded5f72011-10-07 17:15:04 -07002653void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002654 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002655 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002656 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002657 if (IsDexFileRegisteredLocked(dex_file)) {
2658 return;
2659 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002660 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002661 // Don't alloc while holding the lock, since allocation may need to
2662 // suspend all threads and another thread may need the dex_lock_ to
2663 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002664 StackHandleScope<1> hs(self);
2665 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
2666 CHECK(dex_cache.Get() != NULL) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002667 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002668 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002669 if (IsDexFileRegisteredLocked(dex_file)) {
2670 return;
2671 }
2672 RegisterDexFileLocked(dex_file, dex_cache);
2673 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002674}
2675
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002676void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002677 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002678 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002679 RegisterDexFileLocked(dex_file, dex_cache);
2680}
2681
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002682mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002683 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002684 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002685 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002686 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002687 if (dex_cache->GetDexFile() == &dex_file) {
2688 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002689 }
2690 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002691 // Search matching by location name.
2692 std::string location(dex_file.GetLocation());
2693 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002694 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002695 if (dex_cache->GetDexFile()->GetLocation() == location) {
2696 return dex_cache;
2697 }
2698 }
2699 // Failure, dump diagnostic and abort.
2700 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002701 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002702 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
2703 }
2704 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002705 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002706}
2707
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002708void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002709 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08002710 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002711 mirror::DexCache* dex_cache = GetDexCache(i);
2712 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08002713 }
2714}
2715
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002716mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002717 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Ian Rogersa436fde2013-08-27 23:34:06 -07002718 if (UNLIKELY(klass == NULL)) {
2719 return NULL;
2720 }
2721 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002722}
2723
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002724mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
2725 Primitive::Type type) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002726 CHECK(primitive_class != NULL);
Ian Rogers1f539342012-10-03 21:09:42 -07002727 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002728 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002729 StackHandleScope<1> hs(self);
2730 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002731 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002732 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002733 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002734 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
2735 const char* descriptor = Primitive::Descriptor(type);
2736 mirror::Class* existing = InsertClass(descriptor, primitive_class, Hash(descriptor));
Ian Rogersc8982582012-09-07 16:53:25 -07002737 CHECK(existing == NULL) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002738 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07002739}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002740
Brian Carlstrombe977852011-07-19 14:54:54 -07002741// Create an array class (i.e. the class object for the array, not the
2742// array itself). "descriptor" looks like "[C" or "[[[[B" or
2743// "[Ljava/lang/String;".
2744//
2745// If "descriptor" refers to an array of primitives, look up the
2746// primitive type's internally-generated class object.
2747//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002748// "class_loader" is the class loader of the class that's referring to
2749// us. It's used to ensure that we're looking for the element type in
2750// the right context. It does NOT become the class loader for the
2751// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07002752//
2753// Returns NULL with an exception raised on failure.
Ian Rogers98379392014-02-24 16:53:16 -08002754mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002755 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002756 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002757 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002758 StackHandleScope<2> hs(self);
2759 Handle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1, class_loader)));
2760 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002761 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002762 // We need to accept erroneous classes as component types.
2763 component_type.Assign(LookupClass(descriptor + 1, class_loader.Get()));
2764 if (component_type.Get() == nullptr) {
2765 DCHECK(self->IsExceptionPending());
2766 return nullptr;
2767 } else {
2768 self->ClearException();
2769 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002770 }
Ian Rogers2d10b202014-05-12 19:15:18 -07002771 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
2772 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
2773 return nullptr;
2774 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002775 // See if the component type is already loaded. Array classes are
2776 // always associated with the class loader of their underlying
2777 // element type -- an array of Strings goes with the loader for
2778 // java/lang/String -- so we need to look for it there. (The
2779 // caller should have checked for the existence of the class
2780 // before calling here, but they did so with *their* class loader,
2781 // not the component type's loader.)
2782 //
2783 // If we find it, the caller adds "loader" to the class' initiating
2784 // loader list, which should prevent us from going through this again.
2785 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002786 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002787 // are the same, because our caller (FindClass) just did the
2788 // lookup. (Even if we get this wrong we still have correct behavior,
2789 // because we effectively do this lookup again when we add the new
2790 // class to the hash table --- necessary because of possible races with
2791 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002792 if (class_loader.Get() != component_type->GetClassLoader()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002793 mirror::Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002794 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002795 return new_class;
2796 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002797 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002798
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002799 // Fill out the fields in the Class.
2800 //
2801 // It is possible to execute some methods against arrays, because
2802 // all arrays are subclasses of java_lang_Object_, so we need to set
2803 // up a vtable. We can just point at the one in java_lang_Object_.
2804 //
2805 // Array classes are simple enough that we don't need to do a full
2806 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002807 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002808 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002809 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002810 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002811 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002812 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002813 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002814 } else if (strcmp(descriptor, class_roots_descriptors_[kJavaLangStringArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002815 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002816 } else if (strcmp(descriptor,
2817 class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002818 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002819 } else if (strcmp(descriptor,
2820 class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002821 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002822 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002823 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002824 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002825 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002826 }
2827 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002828 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002829 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002830 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002831 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002832 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002833 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002834 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002835 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002836 DCHECK(new_class->GetComponentType() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002837 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002838 new_class->SetSuperClass(java_lang_Object);
2839 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002840 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002841 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002842 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
2843 new_class->PopulateEmbeddedImtAndVTable();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002844 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002845 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002846 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002847
2848
2849 // All arrays have java/lang/Cloneable and java/io/Serializable as
2850 // interfaces. We need to set that up here, so that stuff like
2851 // "instanceof" works right.
2852 //
2853 // Note: The GC could run during the call to FindSystemClass,
2854 // so we need to make sure the class object is GC-valid while we're in
2855 // there. Do this by clearing the interface list so the GC will just
2856 // think that the entries are null.
2857
2858
2859 // Use the single, global copies of "interfaces" and "iftable"
2860 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002861 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002862 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002863 CHECK(array_iftable != nullptr);
2864 new_class->SetIfTable(array_iftable);
2865 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002866
Elliott Hughes00626c22013-06-14 15:04:14 -07002867 // Inherit access flags from the component type.
2868 int access_flags = new_class->GetComponentType()->GetAccessFlags();
2869 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2870 access_flags &= kAccJavaFlagsMask;
2871 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002872 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07002873 access_flags |= kAccAbstract | kAccFinal;
2874 access_flags &= ~kAccInterface;
2875
2876 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002877
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002878 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), Hash(descriptor));
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002879 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002880 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002881 }
2882 // Another thread must have loaded the class after we
2883 // started but before we finished. Abandon what we've
2884 // done.
2885 //
2886 // (Yes, this happens.)
2887
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002888 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002889}
2890
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002891mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07002892 switch (type) {
2893 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002894 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07002895 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002896 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07002897 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002898 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07002899 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002900 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07002901 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002902 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07002903 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002904 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07002905 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002906 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07002907 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002908 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07002909 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002910 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07002911 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002912 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07002913 }
Elliott Hughesbd935992011-08-22 11:59:34 -07002914 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002915 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07002916 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002917}
2918
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002919mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
2920 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002921 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002922 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08002923 std::string source;
2924 if (dex_cache != NULL) {
2925 source += " from ";
2926 source += dex_cache->GetLocation()->ToModifiedUtf8();
2927 }
2928 LOG(INFO) << "Loaded class " << descriptor << source;
2929 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002930 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07002931 mirror::Class* existing =
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002932 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002933 if (existing != NULL) {
2934 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07002935 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002936 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == NULL &&
2937 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002938 // Check a class loaded with the system class loader matches one in the image if the class
2939 // is in the image.
2940 existing = LookupClassFromImage(descriptor);
2941 if (existing != NULL) {
2942 CHECK(klass == existing);
2943 }
2944 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08002945 VerifyObject(klass);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002946 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002947 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002948 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002949 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002950 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002951}
2952
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002953mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
2954 size_t hash) {
2955 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2956 mirror::Class* existing =
2957 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
2958
2959 if (existing == nullptr) {
2960 CHECK(klass->IsProxyClass());
2961 return nullptr;
2962 }
2963
2964 CHECK_NE(existing, klass) << descriptor;
2965 CHECK(!existing->IsResolved()) << descriptor;
2966 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
2967
2968 for (auto it = class_table_.lower_bound(hash), end = class_table_.end(); it != end && it->first == hash;
2969 ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002970 mirror::Class* klass = it->second.Read();
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07002971 if (klass == existing) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002972 class_table_.erase(it);
2973 break;
2974 }
2975 }
2976
2977 CHECK(!klass->IsTemp()) << descriptor;
2978 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
2979 dex_cache_image_class_lookup_required_) {
2980 // Check a class loaded with the system class loader matches one in the image if the class
2981 // is in the image.
2982 existing = LookupClassFromImage(descriptor);
2983 if (existing != nullptr) {
2984 CHECK(klass == existing) << descriptor;
2985 }
2986 }
2987 VerifyObject(klass);
2988
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002989 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002990 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002991 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002992 }
2993
2994 return existing;
2995}
2996
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002997bool ClassLinker::RemoveClass(const char* descriptor, const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002998 size_t hash = Hash(descriptor);
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002999 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Brian Carlstromf3632832014-05-20 15:36:53 -07003000 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3001 it != end && it->first == hash;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003002 ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003003 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003004 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003005 class_table_.erase(it);
Brian Carlstromae826982011-11-09 01:33:42 -08003006 return true;
3007 }
3008 }
3009 return false;
3010}
3011
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003012mirror::Class* ClassLinker::LookupClass(const char* descriptor,
3013 const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003014 size_t hash = Hash(descriptor);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003015 {
3016 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3017 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
3018 if (result != NULL) {
3019 return result;
3020 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003021 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003022 if (class_loader != NULL || !dex_cache_image_class_lookup_required_) {
3023 return NULL;
3024 } else {
3025 // Lookup failed but need to search dex_caches_.
3026 mirror::Class* result = LookupClassFromImage(descriptor);
3027 if (result != NULL) {
3028 InsertClass(descriptor, result, hash);
3029 } else {
3030 // Searching the image dex files/caches failed, we don't want to get into this situation
3031 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3032 // classes into the class table.
3033 const int32_t kMaxFailedDexCacheLookups = 1000;
3034 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3035 MoveImageClassesToClassTable();
3036 }
3037 }
3038 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003039 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003040}
3041
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003042mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
3043 const mirror::ClassLoader* class_loader,
3044 size_t hash) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003045 auto end = class_table_.end();
3046 for (auto it = class_table_.lower_bound(hash); it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003047 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003048 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003049 if (kIsDebugBuild) {
3050 // Check for duplicates in the table.
3051 for (++it; it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003052 mirror::Class* klass2 = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003053 CHECK(!(klass2->GetClassLoader() == class_loader &&
3054 klass2->DescriptorEquals(descriptor)))
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003055 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
3056 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003057 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003058 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003059 return klass;
3060 }
3061 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003062 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003063}
3064
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003065static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3066 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3067 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
3068 CHECK(image != NULL);
3069 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3070 return root->AsObjectArray<mirror::DexCache>();
3071}
3072
3073void ClassLinker::MoveImageClassesToClassTable() {
3074 Thread* self = Thread::Current();
3075 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3076 if (!dex_cache_image_class_lookup_required_) {
3077 return; // All dex cache classes are already in the class table.
3078 }
3079 const char* old_no_suspend_cause =
3080 self->StartAssertNoThreadSuspension("Moving image classes to class table");
3081 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogerscb6b0f32014-08-12 02:30:58 -07003082 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003083 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3084 mirror::DexCache* dex_cache = dex_caches->Get(i);
3085 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3086 for (int32_t j = 0; j < types->GetLength(); j++) {
3087 mirror::Class* klass = types->Get(j);
3088 if (klass != NULL) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003089 DCHECK(klass->GetClassLoader() == NULL);
Ian Rogerscb6b0f32014-08-12 02:30:58 -07003090 const char* descriptor = klass->GetDescriptor(&temp);
3091 size_t hash = Hash(descriptor);
3092 mirror::Class* existing = LookupClassFromTableLocked(descriptor, NULL, hash);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003093 if (existing != NULL) {
3094 CHECK(existing == klass) << PrettyClassAndClassLoader(existing) << " != "
3095 << PrettyClassAndClassLoader(klass);
3096 } else {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003097 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003098 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003099 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003100 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003101 }
3102 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003103 }
3104 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003105 dex_cache_image_class_lookup_required_ = false;
3106 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3107}
3108
3109mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
3110 Thread* self = Thread::Current();
3111 const char* old_no_suspend_cause =
3112 self->StartAssertNoThreadSuspension("Image class lookup");
3113 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3114 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3115 mirror::DexCache* dex_cache = dex_caches->Get(i);
3116 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003117 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003118 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
3119 if (string_id != NULL) {
3120 const DexFile::TypeId* type_id =
3121 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
3122 if (type_id != NULL) {
3123 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3124 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
3125 if (klass != NULL) {
3126 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3127 return klass;
3128 }
3129 }
3130 }
3131 }
3132 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3133 return NULL;
3134}
3135
3136void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3137 result.clear();
3138 if (dex_cache_image_class_lookup_required_) {
3139 MoveImageClassesToClassTable();
3140 }
3141 size_t hash = Hash(descriptor);
3142 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003143 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
Mathieu Chartier02e25112013-08-14 16:14:24 -07003144 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003145 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003146 if (klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003147 result.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003148 }
3149 }
3150}
3151
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003152void ClassLinker::VerifyClass(Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003153 // TODO: assert that the monitor on the Class is held
Ian Rogers1f539342012-10-03 21:09:42 -07003154 Thread* self = Thread::Current();
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003155 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003156
Ian Rogers9ffb0392012-09-10 11:56:50 -07003157 // Don't attempt to re-verify if already sufficiently verified.
3158 if (klass->IsVerified() ||
3159 (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler())) {
jeffhao98eacac2011-09-14 16:11:53 -07003160 return;
3161 }
3162
Ian Rogers9ffb0392012-09-10 11:56:50 -07003163 // The class might already be erroneous, for example at compile time if we attempted to verify
3164 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003165 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003166 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003167 return;
3168 }
3169
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003170 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003171 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003172 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003173 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003174 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003175 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003176 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003177 }
jeffhao98eacac2011-09-14 16:11:53 -07003178
Jeff Hao4a200f52014-04-01 14:58:49 -07003179 // Skip verification if disabled.
3180 if (!Runtime::Current()->IsVerificationEnabled()) {
3181 klass->SetStatus(mirror::Class::kStatusVerified, self);
3182 return;
3183 }
3184
Ian Rogers9ffb0392012-09-10 11:56:50 -07003185 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003186 StackHandleScope<2> hs(self);
3187 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
3188 if (super.Get() != NULL) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003189 // Acquire lock to prevent races on verifying the super class.
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003190 ObjectLock<mirror::Class> lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003191
3192 if (!super->IsVerified() && !super->IsErroneous()) {
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003193 VerifyClass(super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003194 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003195 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003196 std::string error_msg(
3197 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3198 PrettyDescriptor(klass.Get()).c_str(),
3199 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003200 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003201 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3202 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003203 self->ClearException();
3204 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003205 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3206 if (cause.Get() != nullptr) {
3207 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003208 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003209 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003210 if (Runtime::Current()->IsCompiler()) {
3211 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3212 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003213 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003214 return;
3215 }
3216 }
3217
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003218 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003219 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003220 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003221 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003222 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003223 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003224 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003225 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003226 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3227 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003228 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003229 return;
3230 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003231 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003232 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003233 if (!preverified) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003234 verifier_failure = verifier::MethodVerifier::VerifyClass(klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003235 Runtime::Current()->IsCompiler(),
3236 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003237 }
3238 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003239 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003240 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003241 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3242 << " because: " << error_msg;
3243 }
Ian Rogers1f539342012-10-03 21:09:42 -07003244 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003245 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003246 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003247 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003248 // Even though there were no verifier failures we need to respect whether the super-class
3249 // was verified or requiring runtime reverification.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003250 if (super.Get() == NULL || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003251 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003252 } else {
3253 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003254 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003255 // Pretend a soft failure occured so that we don't consider the class verified below.
3256 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003257 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003258 } else {
3259 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3260 // Soft failures at compile time should be retried at runtime. Soft
3261 // failures at runtime will be handled by slow paths in the generated
3262 // code. Set status accordingly.
3263 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003264 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003265 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003266 klass->SetStatus(mirror::Class::kStatusVerified, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003267 }
3268 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003269 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003270 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003271 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3272 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003273 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003274 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003275 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003276 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003277 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003278 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003279 // Let the interpreter know it by setting the kAccPreverified flag onto each
3280 // method.
3281 // Note: we're going here during compilation and at runtime. When we set the
3282 // kAccPreverified flag when compiling image classes, the flag is recorded
3283 // in the image and is set when loading the image.
3284 klass->SetPreverifiedFlagOnAllMethods();
3285 }
jeffhao98eacac2011-09-14 16:11:53 -07003286}
3287
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003288bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3289 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003290 // If we're compiling, we can only verify the class using the oat file if
3291 // we are not compiling the image or if the class we're verifying is not part of
3292 // the app. In other words, we will only check for preverification of bootclasspath
3293 // classes.
3294 if (Runtime::Current()->IsCompiler()) {
3295 // Are we compiling the bootclasspath?
3296 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3297 return false;
3298 }
3299 // We are compiling an app (not the image).
3300
3301 // Is this an app class? (I.e. not a bootclasspath class)
3302 if (klass->GetClassLoader() != NULL) {
3303 return false;
3304 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003305 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003306
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003307 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003308 // Make this work with gtests, which do not set up the image properly.
3309 // TODO: we should clean up gtests to set up the image path properly.
Nicolas Geoffray9c290012014-07-22 10:48:00 +01003310 if (Runtime::Current()->IsCompiler() || (oat_file == NULL)) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003311 return false;
3312 }
3313
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003314 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07003315 uint dex_location_checksum = dex_file.GetLocationChecksum();
Ian Rogers8d31bbd2013-10-13 10:44:14 -07003316 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation().c_str(),
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07003317 &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003318 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003319 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003320 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003321 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3322 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003323 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003324 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003325 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003326 // Compile time verification failed with a soft error. Compile time verification can fail
3327 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003328 // class ... {
3329 // Foo x;
3330 // .... () {
3331 // if (...) {
3332 // v1 gets assigned a type of resolved class Foo
3333 // } else {
3334 // v1 gets assigned a type of unresolved class Bar
3335 // }
3336 // iput x = v1
3337 // } }
3338 // when we merge v1 following the if-the-else it results in Conflict
3339 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3340 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3341 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3342 // at compile time).
3343 return false;
3344 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003345 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003346 // Compile time verification failed with a hard error. This is caused by invalid instructions
3347 // in the class. These errors are unrecoverable.
3348 return false;
3349 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003350 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003351 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3352 // not loading the class.
3353 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3354 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003355 return false;
3356 }
Ian Rogerscb6b0f32014-08-12 02:30:58 -07003357 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003358 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003359 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogerscb6b0f32014-08-12 02:30:58 -07003360 << klass->GetDescriptor(&temp);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003361
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003362 return false;
3363}
3364
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003365void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003366 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003367 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3368 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3369 }
3370 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3371 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3372 }
3373}
3374
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003375void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003376 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003377 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3378 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
3379 if (code_item == NULL) {
3380 return; // native or abstract method
3381 }
3382 if (code_item->tries_size_ == 0) {
3383 return; // nothing to process
3384 }
3385 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
3386 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3387 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3388 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3389 CatchHandlerIterator iterator(handlers_ptr);
3390 for (; iterator.HasNext(); iterator.Next()) {
3391 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3392 // unresolved exception types will be ignored by exception delivery
3393 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003394 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003395 if (exception_type == NULL) {
3396 DCHECK(Thread::Current()->IsExceptionPending());
3397 Thread::Current()->ClearException();
3398 }
3399 }
3400 }
3401 handlers_ptr = iterator.EndDataPointer();
3402 }
3403}
3404
Brian Carlstromea46f952013-07-30 01:26:50 -07003405static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003406static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003407 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003408
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003409mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003410 jobjectArray interfaces, jobject loader,
3411 jobjectArray methods, jobjectArray throws) {
3412 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003413 StackHandleScope<8> hs(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003414 Handle<mirror::Class> klass(hs.NewHandle(
3415 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003416 if (klass.Get() == NULL) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003417 CHECK(self->IsExceptionPending()); // OOME.
3418 return NULL;
3419 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003420 DCHECK(klass->GetClass() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003421 klass->SetObjectSize(sizeof(mirror::Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003422 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003423 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003424 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003425 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003426 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003427 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003428 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003429
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003430 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003431 {
3432 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
3433 if (UNLIKELY(sfields == NULL)) {
3434 CHECK(self->IsExceptionPending()); // OOME.
3435 return NULL;
3436 }
3437 klass->SetSFields(sfields);
3438 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003439 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3440 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003441 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3442 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003443 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003444 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003445 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003446 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003447 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003448 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003449 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3450 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003451 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3452 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003453 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003454 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003455 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003456 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003457 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003458 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003459 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003460
Ian Rogers466bb252011-10-14 03:29:56 -07003461 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003462 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003463 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003464 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003465 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003466 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003467 }
3468 klass->SetDirectMethods(directs);
3469 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003470 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003471 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003472 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003473 }
3474 klass->SetDirectMethod(0, constructor);
3475 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003476
Mathieu Chartier590fee92013-09-13 13:46:47 -07003477 // Create virtual method using specified prototypes.
3478 size_t num_virtual_methods =
3479 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003480 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003481 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3482 num_virtual_methods);
Ian Rogersa436fde2013-08-27 23:34:06 -07003483 if (UNLIKELY(virtuals == NULL)) {
3484 CHECK(self->IsExceptionPending()); // OOME.
3485 return NULL;
3486 }
3487 klass->SetVirtualMethods(virtuals);
3488 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003489 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003490 StackHandleScope<1> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003491 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3492 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003493 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003494 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003495 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003496 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003497 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003498 }
3499 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003500 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003501
3502 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003503 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003504 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003505
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003506 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3507 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003508 {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003509 ObjectLock<mirror::Class> resolution_lock(self, klass); // Must hold lock on object when resolved.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003510 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003511 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003512 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003513 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003514 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003515 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003516 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003517 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003518
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003519 CHECK(klass->IsRetired());
3520 CHECK_NE(klass.Get(), new_class);
3521 klass.Assign(new_class);
3522
3523 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
3524 interfaces_sfield->SetObject<false>(klass.Get(), soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
3525 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
3526 throws_sfield->SetObject<false>(klass.Get(), soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
3527
3528 {
3529 // Lock on klass is released. Lock new class object.
3530 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003531 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003532 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003533
3534 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003535 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003536 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003537 CheckProxyConstructor(klass->GetDirectMethod(0));
3538 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003539 StackHandleScope<2> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003540 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3541 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003542 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003543 Handle<mirror::ArtMethod> virtual_method(hs.NewHandle(klass->GetVirtualMethod(i)));
3544 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003545 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003546
Mathieu Chartier590fee92013-09-13 13:46:47 -07003547 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003548 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003549 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003550 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3551
3552 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003553 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003554 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003555
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003556 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003557 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003558 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003559 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003560 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003561 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003562 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003563 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003564}
3565
Ian Rogersef7d42f2014-01-06 12:55:46 -08003566std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003567 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003568 mirror::String* name = proxy_class->GetName();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003569 DCHECK(name != NULL);
3570 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3571}
3572
Ian Rogersef7d42f2014-01-06 12:55:46 -08003573mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3574 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003575 DCHECK(proxy_class->IsProxyClass());
3576 DCHECK(proxy_method->IsProxyMethod());
3577 // Locate the dex cache of the original interface/Object
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003578 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003579 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003580 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003581 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003582 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003583 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003584 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003585 break;
3586 }
3587 }
3588 }
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003589 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003590 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003591 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003592 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003593 return resolved_method;
3594}
3595
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003596
Brian Carlstromea46f952013-07-30 01:26:50 -07003597mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003598 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003599 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003600 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003601 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003602 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003603 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3604 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Jeff Hao95b4c652014-08-14 17:18:52 -07003605 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3606 // code_ too)
Jeff Hao4bf8d112014-07-24 16:26:09 -07003607 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3608 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003609 CHECK(self->IsExceptionPending()); // OOME.
Jeff Hao4bf8d112014-07-24 16:26:09 -07003610 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003611 }
Ian Rogers466bb252011-10-14 03:29:56 -07003612 // Make this constructor public and fix the class to be our Proxy version
3613 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003614 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003615 return constructor;
3616}
3617
Brian Carlstromea46f952013-07-30 01:26:50 -07003618static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003619 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003620 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003621 CHECK_STREQ(constructor->GetName(), "<init>");
3622 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3623 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003624 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003625}
3626
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003627mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003628 Handle<mirror::Class> klass,
3629 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003630 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3631 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08003632 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003633 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003634 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003635 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003636 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Ian Rogersa436fde2013-08-27 23:34:06 -07003637 if (UNLIKELY(method == NULL)) {
3638 CHECK(self->IsExceptionPending()); // OOME.
3639 return NULL;
3640 }
Ian Rogers466bb252011-10-14 03:29:56 -07003641
3642 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3643 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003644 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07003645 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003646
Ian Rogers466bb252011-10-14 03:29:56 -07003647 // At runtime the method looks like a reference and argument saving method, clone the code
3648 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003649 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
3650 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07003651 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08003652
Ian Rogersc2b44472011-12-14 21:17:17 -08003653 return method;
3654}
Jesse Wilson95caa792011-10-12 18:14:17 -04003655
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003656static void CheckProxyMethod(Handle<mirror::ArtMethod> method, Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003657 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003658 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003659 CHECK(!prototype->IsFinal());
3660 CHECK(method->IsFinal());
3661 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08003662
3663 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
3664 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
3665 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003666 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
3667 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08003668 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
3669
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003670 MethodHelper mh(method);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003671 MethodHelper mh2(prototype);
3672 CHECK_STREQ(method->GetName(), prototype->GetName());
3673 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07003674 // More complex sanity - via dex cache
Ian Rogers19846512012-02-24 11:42:47 -08003675 CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04003676}
3677
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003678static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
3679 bool can_init_parents)
3680 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003681 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003682 return true;
3683 }
3684 if (!can_init_statics) {
3685 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07003686 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003687 if (clinit != NULL) {
3688 return false;
3689 }
3690 // Check if there are encoded static values needing initialization.
3691 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003692 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003693 DCHECK(dex_class_def != NULL);
3694 if (dex_class_def->static_values_off_ != 0) {
3695 return false;
3696 }
3697 }
3698 }
3699 if (!klass->IsInterface() && klass->HasSuperClass()) {
3700 mirror::Class* super_class = klass->GetSuperClass();
3701 if (!can_init_parents && !super_class->IsInitialized()) {
3702 return false;
3703 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003704 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003705 return false;
3706 }
3707 }
3708 }
3709 return true;
3710}
3711
Mathieu Chartier590fee92013-09-13 13:46:47 -07003712bool ClassLinker::IsInitialized() const {
3713 return init_done_;
3714}
3715
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003716bool ClassLinker::InitializeClass(Handle<mirror::Class> klass, bool can_init_statics,
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003717 bool can_init_parents) {
3718 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
3719
3720 // Are we already initialized and therefore done?
3721 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
3722 // an initialized class will never change its state.
3723 if (klass->IsInitialized()) {
3724 return true;
3725 }
3726
3727 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003728 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003729 return false;
3730 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003731
Carl Shapirob5573532011-07-12 18:22:59 -07003732 Thread* self = Thread::Current();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003733 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003734 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003735 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003736
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003737 // Re-check under the lock in case another thread initialized ahead of us.
3738 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003739 return true;
3740 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003741
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003742 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003743 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003744 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromd1422f82011-09-28 11:37:09 -07003745 return false;
3746 }
3747
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003748 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003749
3750 if (!klass->IsVerified()) {
jeffhao98eacac2011-09-14 16:11:53 -07003751 VerifyClass(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003752 if (!klass->IsVerified()) {
3753 // We failed to verify, expect either the klass to be erroneous or verification failed at
3754 // compile time.
3755 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07003756 CHECK(self->IsExceptionPending());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003757 } else {
3758 CHECK(Runtime::Current()->IsCompiler());
3759 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07003760 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003761 return false;
3762 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003763 }
3764
Brian Carlstromd1422f82011-09-28 11:37:09 -07003765 // If the class is kStatusInitializing, either this thread is
3766 // initializing higher up the stack or another thread has beat us
3767 // to initializing and we need to wait. Either way, this
3768 // invocation of InitializeClass will not be responsible for
3769 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003770 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07003771 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07003772 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003773 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003774 return true;
3775 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003776 // No. That's fine. Wait for another thread to finish initializing.
3777 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003778 }
3779
3780 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003781 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003782 return false;
3783 }
3784
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003785 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003786
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003787 // From here out other threads may observe that we're initializing and so changes of state
3788 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07003789 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003790 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003791
3792 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003793 }
3794
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003795 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003796 if (!klass->IsInterface() && klass->HasSuperClass()) {
3797 mirror::Class* super_class = klass->GetSuperClass();
3798 if (!super_class->IsInitialized()) {
3799 CHECK(!super_class->IsInterface());
3800 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003801 StackHandleScope<1> hs(self);
3802 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
3803 bool super_initialized = InitializeClass(handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003804 if (!super_initialized) {
3805 // The super class was verified ahead of entering initializing, we should only be here if
3806 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003807 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07003808 << "Super class initialization failed for "
3809 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003810 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003811 << "\nPending exception:\n"
3812 << (self->GetException(NULL) != NULL ? self->GetException(NULL)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003813 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003814 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003815 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003816 return false;
3817 }
Ian Rogers1bddec32012-02-04 12:27:34 -08003818 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003819 }
3820
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003821 if (klass->NumStaticFields() > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003822 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003823 CHECK(dex_class_def != NULL);
Mathieu Chartierf8322842014-05-16 10:59:25 -07003824 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003825 StackHandleScope<2> hs(self);
3826 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07003827 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07003828 EncodedStaticFieldValueIterator it(dex_file, &dex_cache, &class_loader,
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003829 this, *dex_class_def);
3830 if (it.HasNext()) {
3831 CHECK(can_init_statics);
Brian Carlstromf3632832014-05-20 15:36:53 -07003832 // We reordered the fields, so we need to be able to map the
3833 // field indexes to the right fields.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003834 SafeMap<uint32_t, mirror::ArtField*> field_map;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003835 ConstructFieldMap(dex_file, *dex_class_def, klass.Get(), field_map);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003836 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003837 if (Runtime::Current()->IsActiveTransaction()) {
3838 it.ReadValueToField<true>(field_map.Get(i));
3839 } else {
3840 it.ReadValueToField<false>(field_map.Get(i));
3841 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003842 }
3843 }
3844 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003845
Ian Rogersd91d6d62013-09-25 20:26:14 -07003846 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003847 if (clinit != NULL) {
3848 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07003849 JValue result;
3850 clinit->Invoke(self, NULL, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003851 }
3852
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003853 uint64_t t1 = NanoTime();
3854
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003855 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003856 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003857 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003858
3859 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07003860 WrapExceptionInInitializer();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003861 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003862 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003863 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003864 RuntimeStats* global_stats = Runtime::Current()->GetStats();
3865 RuntimeStats* thread_stats = self->GetStats();
3866 ++global_stats->class_init_count;
3867 ++thread_stats->class_init_count;
3868 global_stats->class_init_time_ns += (t1 - t0);
3869 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003870 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003871 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003872 if (VLOG_IS_ON(class_linker)) {
Ian Rogerscb6b0f32014-08-12 02:30:58 -07003873 std::string temp;
3874 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07003875 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08003876 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08003877 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003878 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003879 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003880 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003881 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003882}
3883
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003884bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003885 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003886 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003887 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003888 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003889 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08003890 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003891
3892 // When we wake up, repeat the test for init-in-progress. If
3893 // there's an exception pending (only possible if
3894 // "interruptShouldThrow" was set), bail out.
3895 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07003896 WrapExceptionInInitializer();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003897 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003898 return false;
3899 }
3900 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003901 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003902 continue;
3903 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003904 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07003905 // Compile time initialization failed.
3906 return false;
3907 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003908 if (klass->IsErroneous()) {
3909 // The caller wants an exception, but it was thrown in a
3910 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07003911 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003912 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07003913 return false;
3914 }
3915 if (klass->IsInitialized()) {
3916 return true;
3917 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003918 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003919 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003920 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003921 LOG(FATAL) << "Not Reached" << PrettyClass(klass.Get());
Brian Carlstromd1422f82011-09-28 11:37:09 -07003922}
3923
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003924bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003925 if (klass->IsInterface()) {
3926 return true;
3927 }
Ian Rogers151f2212014-05-06 11:27:27 -07003928 // Begin with the methods local to the superclass.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003929 StackHandleScope<2> hs(Thread::Current());
3930 MethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
3931 MethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003932 if (klass->HasSuperClass() &&
3933 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07003934 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
3935 mh.ChangeMethod(klass->GetVTableEntry(i));
3936 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003937 if (mh.GetMethod() != super_mh.GetMethod() &&
3938 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
3939 ThrowLinkageError(klass.Get(),
3940 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003941 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07003942 PrettyMethod(mh.GetMethod()).c_str(),
3943 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003944 return false;
3945 }
3946 }
3947 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003948 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07003949 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
3950 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
3951 for (uint32_t j = 0; j < num_methods; ++j) {
3952 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
3953 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003954 if (mh.GetMethod() != super_mh.GetMethod() &&
3955 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
3956 ThrowLinkageError(klass.Get(),
3957 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003958 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07003959 PrettyMethod(mh.GetMethod()).c_str(),
3960 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003961 return false;
3962 }
3963 }
3964 }
3965 }
3966 return true;
3967}
3968
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003969bool ClassLinker::EnsureInitialized(Handle<mirror::Class> c, bool can_init_fields,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003970 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003971 DCHECK(c.Get() != nullptr);
3972 const bool success = c->IsInitialized() || InitializeClass(c, can_init_fields, can_init_parents);
3973 if (!success && can_init_fields && can_init_parents) {
3974 CHECK(Thread::Current()->IsExceptionPending()) << PrettyClass(c.Get());
Ian Rogers595799e2012-01-11 17:32:51 -08003975 }
3976 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07003977}
3978
Elliott Hughes5fe594f2011-09-08 12:33:17 -07003979void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003980 mirror::Class* c,
3981 SafeMap<uint32_t, mirror::ArtField*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07003982 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07003983 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003984 StackHandleScope<2> hs(Thread::Current());
3985 Handle<mirror::DexCache> dex_cache(hs.NewHandle(c->GetDexCache()));
3986 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(c->GetClassLoader()));
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003987 CHECK(!kMovingFields);
Ian Rogers0571d352011-11-03 19:51:38 -07003988 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003989 field_map.Put(i, ResolveField(dex_file, it.GetMemberIndex(), dex_cache, class_loader, true));
Elliott Hughes5fe594f2011-09-08 12:33:17 -07003990 }
3991}
3992
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003993void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
3994 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
3995 if (fields != nullptr) {
3996 for (int index = 0; index < fields->GetLength(); index ++) {
3997 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
3998 fields->Get(index)->SetDeclaringClass(new_class);
3999 }
4000 }
4001 }
4002
4003 fields = new_class->GetSFields();
4004 if (fields != nullptr) {
4005 for (int index = 0; index < fields->GetLength(); index ++) {
4006 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4007 fields->Get(index)->SetDeclaringClass(new_class);
4008 }
4009 }
4010 }
4011
4012 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4013 if (methods != nullptr) {
4014 for (int index = 0; index < methods->GetLength(); index ++) {
4015 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4016 methods->Get(index)->SetDeclaringClass(new_class);
4017 }
4018 }
4019 }
4020
4021 methods = new_class->GetVirtualMethods();
4022 if (methods != nullptr) {
4023 for (int index = 0; index < methods->GetLength(); index ++) {
4024 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4025 methods->Get(index)->SetDeclaringClass(new_class);
4026 }
4027 }
4028 }
4029}
4030
4031bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4032 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4033 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004034 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004035
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004036 if (!LinkSuperClass(klass)) {
4037 return false;
4038 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004039 if (!LinkMethods(self, klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004040 return false;
4041 }
4042 if (!LinkInstanceFields(klass)) {
4043 return false;
4044 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004045 size_t class_size;
4046 if (!LinkStaticFields(klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004047 return false;
4048 }
4049 CreateReferenceInstanceOffsets(klass);
4050 CreateReferenceStaticOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004051 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004052
4053 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4054 // We don't need to retire this class as it has no embedded tables or it was created the
4055 // correct size during class linker initialization.
4056 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4057
4058 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
4059 klass->PopulateEmbeddedImtAndVTable();
4060 }
4061
4062 // This will notify waiters on klass that saw the not yet resolved
4063 // class in the class_table_ during EnsureResolved.
4064 klass->SetStatus(mirror::Class::kStatusResolved, self);
4065 *new_class = klass.Get();
4066 } else {
4067 CHECK(!klass->IsResolved());
4068 // Retire the temporary class and create the correctly sized resolved class.
4069 *new_class = klass->CopyOf(self, class_size);
4070 if (UNLIKELY(*new_class == NULL)) {
4071 CHECK(self->IsExceptionPending()); // Expect an OOME.
4072 klass->SetStatus(mirror::Class::kStatusError, self);
4073 return false;
4074 }
4075
4076 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4077 StackHandleScope<1> hs(self);
4078 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4079 ObjectLock<mirror::Class> lock(self, new_class_h);
4080
4081 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4082
4083 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(), Hash(descriptor));
4084 CHECK(existing == NULL || existing == klass.Get());
4085
4086 // This will notify waiters on temp class that saw the not yet resolved class in the
4087 // class_table_ during EnsureResolved.
4088 klass->SetStatus(mirror::Class::kStatusRetired, self);
4089
4090 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4091 // This will notify waiters on new_class that saw the not yet resolved
4092 // class in the class_table_ during EnsureResolved.
4093 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004094 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004095 return true;
4096}
4097
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004098bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004099 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004100 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4101 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004102 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004103 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004104 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004105 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004106 return false;
4107 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004108 // Verify
4109 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004110 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004111 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004112 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004113 return false;
4114 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004115 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004116 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004117 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004118 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004119 if (interfaces != NULL) {
4120 for (size_t i = 0; i < interfaces->Size(); i++) {
4121 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004122 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004123 if (interface == NULL) {
4124 DCHECK(Thread::Current()->IsExceptionPending());
4125 return false;
4126 }
4127 // Verify
4128 if (!klass->CanAccess(interface)) {
4129 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004130 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004131 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004132 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004133 return false;
4134 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004135 }
4136 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004137 // Mark the class as loaded.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004138 klass->SetStatus(mirror::Class::kStatusLoaded, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004139 return true;
4140}
4141
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004142bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004143 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004144 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004145 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004146 if (super != NULL) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004147 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004148 return false;
4149 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004150 return true;
4151 }
4152 if (super == NULL) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004153 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4154 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004155 return false;
4156 }
4157 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004158 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004159 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004160 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004161 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004162 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004163 return false;
4164 }
4165 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004166 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004167 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004168 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004169 return false;
4170 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004171
Brian Carlstromf3632832014-05-20 15:36:53 -07004172 // Inherit kAccClassIsFinalizable from the superclass in case this
4173 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004174 if (super->IsFinalizable()) {
4175 klass->SetFinalizable();
4176 }
4177
Elliott Hughes2da50362011-10-10 16:57:08 -07004178 // Inherit reference flags (if any) from the superclass.
4179 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4180 if (reference_flags != 0) {
4181 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4182 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004183 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004184 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004185 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004186 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004187 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004188 return false;
4189 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004190
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004191 if (kIsDebugBuild) {
4192 // Ensure super classes are fully resolved prior to resolving fields..
4193 while (super != NULL) {
4194 CHECK(super->IsResolved());
4195 super = super->GetSuperClass();
4196 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004197 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004198 return true;
4199}
4200
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004201// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004202bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004203 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004204 if (klass->IsInterface()) {
4205 // No vtable.
4206 size_t count = klass->NumVirtualMethods();
4207 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004208 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004209 return false;
4210 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004211 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004212 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004213 }
jeffhaobdb76512011-09-07 11:43:16 -07004214 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004215 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004216 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07004217 // Link virtual and interface method tables
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004218 return LinkVirtualMethods(self, klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004219 }
4220 return true;
4221}
4222
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004223bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004224 if (klass->HasSuperClass()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004225 uint32_t max_count = klass->NumVirtualMethods() +
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004226 klass->GetSuperClass()->GetVTableLength();
4227 size_t actual_count = klass->GetSuperClass()->GetVTableLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004228 CHECK_LE(actual_count, max_count);
Mingyao Yang82546342014-08-13 14:51:03 -07004229 StackHandleScope<4> hs(self);
4230 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004231 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004232 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4233 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4234 if (UNLIKELY(vtable.Get() == nullptr)) {
4235 CHECK(self->IsExceptionPending()); // OOME.
4236 return false;
4237 }
4238 int len = super_class->GetVTableLength();
Mingyao Yang1a128582014-07-22 17:33:25 -07004239 for (int i = 0; i < len; i++) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004240 vtable->Set<false>(i, super_class->GetVTableEntry(i));
4241 }
4242 } else {
Mingyao Yang82546342014-08-13 14:51:03 -07004243 CHECK(super_class->GetVTable() != nullptr) << PrettyClass(super_class.Get());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004244 vtable = hs.NewHandle(super_class->GetVTable()->CopyOf(self, max_count));
4245 if (UNLIKELY(vtable.Get() == nullptr)) {
4246 CHECK(self->IsExceptionPending()); // OOME.
4247 return false;
4248 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004249 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004250
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004251 // See if any of our virtual methods override the superclass.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004252 MethodHelper local_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4253 MethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004254 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004255 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004256 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004257 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004258 for (; j < actual_count; ++j) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004259 mirror::ArtMethod* super_method = vtable->Get(j);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004260 super_mh.ChangeMethod(super_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004261 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004262 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4263 super_method->GetAccessFlags())) {
Elliott Hughes39717372012-07-13 16:21:23 -07004264 if (super_method->IsFinal()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004265 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
Elliott Hughes39717372012-07-13 16:21:23 -07004266 PrettyMethod(local_method).c_str(),
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004267 super_method->GetDeclaringClassDescriptor());
Elliott Hughes39717372012-07-13 16:21:23 -07004268 return false;
4269 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004270 vtable->Set<false>(j, local_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004271 local_method->SetMethodIndex(j);
4272 break;
4273 } else {
4274 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method)
4275 << " would have incorrectly overridden the package-private method in "
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004276 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004277 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004278 }
4279 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004280 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004281 // Not overriding, append.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004282 vtable->Set<false>(actual_count, local_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004283 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004284 actual_count += 1;
4285 }
4286 }
4287 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004288 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004289 return false;
4290 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004291 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004292 CHECK_LE(actual_count, max_count);
4293 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004294 vtable.Assign(vtable->CopyOf(self, actual_count));
4295 if (UNLIKELY(vtable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004296 CHECK(self->IsExceptionPending()); // OOME.
4297 return false;
4298 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004299 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004300 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004301 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004302 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004303 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004304 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004305 ThrowClassFormatError(klass.Get(), "Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004306 return false;
4307 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004308 StackHandleScope<1> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004309 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004310 vtable(hs.NewHandle(AllocArtMethodArray(self, num_virtual_methods)));
4311 if (UNLIKELY(vtable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004312 CHECK(self->IsExceptionPending()); // OOME.
4313 return false;
4314 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004315 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004316 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004317 vtable->Set<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004318 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004319 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004320 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004321 }
4322 return true;
4323}
4324
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004325bool ClassLinker::LinkInterfaceMethods(Handle<mirror::Class> klass,
4326 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004327 Thread* const self = Thread::Current();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004328 Runtime* const runtime = Runtime::Current();
Jeff Hao88474b42013-10-23 16:24:40 -07004329 // Set the imt table to be all conflicts by default.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004330 klass->SetImTable(runtime->GetDefaultImt());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004331 size_t super_ifcount;
4332 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004333 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004334 } else {
4335 super_ifcount = 0;
4336 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07004337 uint32_t num_interfaces =
4338 interfaces.Get() == nullptr ? klass->NumDirectInterfaces() : interfaces->GetLength();
4339 size_t ifcount = super_ifcount + num_interfaces;
4340 for (size_t i = 0; i < num_interfaces; i++) {
4341 mirror::Class* interface =
4342 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4343 interfaces->Get(i);
4344 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004345 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004346 if (ifcount == 0) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004347 // Class implements no interfaces.
4348 DCHECK_EQ(klass->GetIfTableCount(), 0);
4349 DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004350 return true;
4351 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004352 if (ifcount == super_ifcount) {
4353 // Class implements same interfaces as parent, are any of these not marker interfaces?
4354 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004355 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Ian Rogers9bc81912012-10-11 21:43:36 -07004356 for (size_t i = 0; i < ifcount; ++i) {
4357 if (super_iftable->GetMethodArrayCount(i) > 0) {
4358 has_non_marker_interface = true;
4359 break;
4360 }
4361 }
4362 if (!has_non_marker_interface) {
4363 // Class just inherits marker interfaces from parent so recycle parent's iftable.
4364 klass->SetIfTable(super_iftable);
4365 return true;
4366 }
4367 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004368 StackHandleScope<4> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004369 Handle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
4370 if (UNLIKELY(iftable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004371 CHECK(self->IsExceptionPending()); // OOME.
4372 return false;
4373 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004374 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004375 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004376 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004377 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004378 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004379 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004380 }
4381 // Flatten the interface inheritance hierarchy.
4382 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004383 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004384 mirror::Class* interface =
Mathieu Chartierf8322842014-05-16 10:59:25 -07004385 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4386 interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004387 DCHECK(interface != NULL);
4388 if (!interface->IsInterface()) {
Ian Rogerscb6b0f32014-08-12 02:30:58 -07004389 std::string temp;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004390 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4391 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogerscb6b0f32014-08-12 02:30:58 -07004392 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004393 return false;
4394 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004395 // Check if interface is already in iftable
4396 bool duplicate = false;
4397 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004398 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004399 if (existing_interface == interface) {
4400 duplicate = true;
4401 break;
4402 }
4403 }
4404 if (!duplicate) {
4405 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004406 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004407 // Add this interface's non-duplicate super-interfaces.
4408 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004409 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004410 bool super_duplicate = false;
4411 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004412 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004413 if (existing_interface == super_interface) {
4414 super_duplicate = true;
4415 break;
4416 }
4417 }
4418 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004419 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004420 }
4421 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004422 }
4423 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004424 // Shrink iftable in case duplicates were found
4425 if (idx < ifcount) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004426 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
4427 if (UNLIKELY(iftable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004428 CHECK(self->IsExceptionPending()); // OOME.
4429 return false;
4430 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004431 ifcount = idx;
4432 } else {
4433 CHECK_EQ(idx, ifcount);
4434 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004435 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004436
4437 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004438 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004439 return true;
4440 }
Jeff Hao88474b42013-10-23 16:24:40 -07004441 // Allocate imtable
4442 bool imtable_changed = false;
Ian Rogers700a4022014-05-19 16:49:03 -07004443 Handle<mirror::ObjectArray<mirror::ArtMethod>> imtable(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004444 hs.NewHandle(AllocArtMethodArray(self, mirror::Class::kImtSize)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004445 if (UNLIKELY(imtable.Get() == NULL)) {
Jeff Hao88474b42013-10-23 16:24:40 -07004446 CHECK(self->IsExceptionPending()); // OOME.
4447 return false;
4448 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004449 MethodHelper interface_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4450 MethodHelper vtable_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Brian Carlstromea46f952013-07-30 01:26:50 -07004451 std::vector<mirror::ArtMethod*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004452 for (size_t i = 0; i < ifcount; ++i) {
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004453 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004454 if (num_methods > 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004455 StackHandleScope<2> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004456 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004457 method_array(hs.NewHandle(AllocArtMethodArray(self, num_methods)));
4458 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004459 CHECK(self->IsExceptionPending()); // OOME.
4460 return false;
4461 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004462 iftable->SetMethodArray(i, method_array.Get());
Ian Rogers700a4022014-05-19 16:49:03 -07004463 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004464 hs.NewHandle(klass->GetVTableDuringLinking()));
Ian Rogers62d6c772013-02-27 08:32:07 -08004465 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004466 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004467 interface_mh.ChangeMethod(interface_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004468 int32_t k;
4469 // For each method listed in the interface's method list, find the
4470 // matching method in our class's method list. We want to favor the
4471 // subclass over the superclass, which just requires walking
4472 // back from the end of the vtable. (This only matters if the
4473 // superclass defines a private method and this class redefines
4474 // it -- otherwise it would use the same vtable slot. In .dex files
4475 // those don't end up in the virtual method table, so it shouldn't
4476 // matter which direction we go. We walk it backward anyway.)
4477 for (k = vtable->GetLength() - 1; k >= 0; --k) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004478 mirror::ArtMethod* vtable_method = vtable->Get(k);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004479 vtable_mh.ChangeMethod(vtable_method);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004480 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Elliott Hughes68243612013-02-22 17:16:07 -08004481 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004482 ThrowIllegalAccessError(
4483 klass.Get(),
4484 "Method '%s' implementing interface method '%s' is not public",
4485 PrettyMethod(vtable_method).c_str(),
4486 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004487 return false;
4488 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004489 method_array->Set<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004490 // Place method in imt if entry is empty, place conflict otherwise.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004491 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
Jeff Hao88474b42013-10-23 16:24:40 -07004492 if (imtable->Get(imt_index) == NULL) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004493 imtable->Set<false>(imt_index, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004494 imtable_changed = true;
4495 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004496 imtable->Set<false>(imt_index, runtime->GetImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -07004497 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004498 break;
4499 }
4500 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004501 if (k < 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004502 StackHandleScope<1> hs(self);
4503 auto miranda_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004504 for (mirror::ArtMethod* mir_method : miranda_list) {
4505 vtable_mh.ChangeMethod(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004506 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004507 miranda_method.Assign(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004508 break;
4509 }
4510 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004511 if (miranda_method.Get() == NULL) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004512 // Point the interface table at a phantom slot.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004513 miranda_method.Assign(down_cast<mirror::ArtMethod*>(interface_method->Clone(self)));
4514 if (UNLIKELY(miranda_method.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004515 CHECK(self->IsExceptionPending()); // OOME.
4516 return false;
4517 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004518 // TODO: If a methods move then the miranda_list may hold stale references.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004519 miranda_list.push_back(miranda_method.Get());
Ian Rogers9bc81912012-10-11 21:43:36 -07004520 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004521 method_array->Set<false>(j, miranda_method.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004522 }
4523 }
4524 }
4525 }
Jeff Hao88474b42013-10-23 16:24:40 -07004526 if (imtable_changed) {
4527 // Fill in empty entries in interface method table with conflict.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004528 mirror::ArtMethod* imt_conflict_method = runtime->GetImtConflictMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004529 for (size_t i = 0; i < mirror::Class::kImtSize; i++) {
Jeff Hao88474b42013-10-23 16:24:40 -07004530 if (imtable->Get(i) == NULL) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004531 imtable->Set<false>(i, imt_conflict_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004532 }
4533 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004534 klass->SetImTable(imtable.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004535 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004536 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004537 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07004538 int new_method_count = old_method_count + miranda_list.size();
Ian Rogersa436fde2013-08-27 23:34:06 -07004539 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4540 if (old_method_count == 0) {
4541 virtuals = AllocArtMethodArray(self, new_method_count);
4542 } else {
4543 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4544 }
4545 if (UNLIKELY(virtuals == NULL)) {
4546 CHECK(self->IsExceptionPending()); // OOME.
4547 return false;
4548 }
4549 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004550
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004551 StackHandleScope<1> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004552 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004553 hs.NewHandle(klass->GetVTableDuringLinking()));
4554 CHECK(vtable.Get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004555 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07004556 int new_vtable_count = old_vtable_count + miranda_list.size();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004557 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
4558 if (UNLIKELY(vtable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004559 CHECK(self->IsExceptionPending()); // OOME.
4560 return false;
4561 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004562 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004563 mirror::ArtMethod* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07004564 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07004565 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4566 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4567 klass->SetVirtualMethod(old_method_count + i, method);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004568 vtable->Set<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004569 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004570 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004571 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004572 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004573
Brian Carlstromea46f952013-07-30 01:26:50 -07004574 mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking();
Elliott Hughes4681c802011-09-25 18:04:37 -07004575 for (int i = 0; i < vtable->GetLength(); ++i) {
4576 CHECK(vtable->Get(i) != NULL);
4577 }
4578
4579// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
4580
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004581 return true;
4582}
4583
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004584bool ClassLinker::LinkInstanceFields(Handle<mirror::Class> klass) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004585 CHECK(klass.Get() != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004586 return LinkFields(klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004587}
4588
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004589bool ClassLinker::LinkStaticFields(Handle<mirror::Class> klass, size_t* class_size) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004590 CHECK(klass.Get() != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004591 return LinkFields(klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004592}
4593
Brian Carlstromdbc05252011-09-09 01:59:59 -07004594struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004595 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4596 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004597 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004598 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004599 NO_THREAD_SAFETY_ANALYSIS {
Brian Carlstromdbc05252011-09-09 01:59:59 -07004600 // First come reference fields, then 64-bit, and finally 32-bit
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004601 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
4602 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08004603 if (type1 != type2) {
4604 bool is_primitive1 = type1 != Primitive::kPrimNot;
4605 bool is_primitive2 = type2 != Primitive::kPrimNot;
Brian Carlstromf3632832014-05-20 15:36:53 -07004606 bool is64bit1 = is_primitive1 && (type1 == Primitive::kPrimLong ||
4607 type1 == Primitive::kPrimDouble);
4608 bool is64bit2 = is_primitive2 && (type2 == Primitive::kPrimLong ||
4609 type2 == Primitive::kPrimDouble);
Ian Rogersef7d42f2014-01-06 12:55:46 -08004610 int order1 = !is_primitive1 ? 0 : (is64bit1 ? 1 : 2);
4611 int order2 = !is_primitive2 ? 0 : (is64bit2 ? 1 : 2);
4612 if (order1 != order2) {
4613 return order1 < order2;
4614 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07004615 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07004616 // same basic group? then sort by string.
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004617 return strcmp(field1->GetName(), field2->GetName()) < 0;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004618 }
4619};
4620
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004621bool ClassLinker::LinkFields(Handle<mirror::Class> klass, bool is_static, size_t* class_size) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004622 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004623 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004624
Brian Carlstromea46f952013-07-30 01:26:50 -07004625 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004626 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004627
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004628 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07004629 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004630 if (is_static) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004631 uint32_t base = sizeof(mirror::Class); // Static fields come after the class.
4632 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
4633 // Static fields come after the embedded tables.
4634 base = mirror::Class::ComputeClassSize(true, klass->GetVTableDuringLinking()->GetLength(),
4635 0, 0, 0);
4636 }
4637 field_offset = MemberOffset(base);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004638 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004639 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004640 if (super_class != NULL) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004641 CHECK(super_class->IsResolved())
4642 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004643 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004644 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004645 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004646
Brian Carlstromf3632832014-05-20 15:36:53 -07004647 CHECK_EQ(num_fields == 0, fields == NULL) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004648
Brian Carlstromdbc05252011-09-09 01:59:59 -07004649 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07004650 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07004651 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004652 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004653 mirror::ArtField* f = fields->Get(i);
Brian Carlstromf3632832014-05-20 15:36:53 -07004654 CHECK(f != NULL) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004655 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004656 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07004657 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
4658 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07004659
4660 // References should be at the front.
4661 size_t current_field = 0;
4662 size_t num_reference_fields = 0;
4663 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004664 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004665 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004666 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004667 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004668 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004669 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07004670 grouped_and_sorted_fields.pop_front();
4671 num_reference_fields++;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004672 fields->Set<false>(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004673 field->SetOffset(field_offset);
4674 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004675 }
4676
4677 // Now we want to pack all of the double-wide fields together. If
4678 // we're not aligned, though, we want to shuffle one 32-bit field
4679 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07004680 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07004681 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004682 mirror::ArtField* field = grouped_and_sorted_fields[i];
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004683 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstromf3632832014-05-20 15:36:53 -07004684 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004685 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07004686 continue;
4687 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004688 fields->Set<false>(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004689 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004690 // drop the consumed field
4691 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
4692 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004693 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07004694 // whether we found a 32-bit field for padding or not, we advance
4695 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004696 }
4697
4698 // Alignment is good, shuffle any double-wide fields forward, and
4699 // finish assigning field offsets to all fields.
Brian Carlstromf3632832014-05-20 15:36:53 -07004700 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()))
4701 << PrettyClass(klass.Get());
Brian Carlstromdbc05252011-09-09 01:59:59 -07004702 while (!grouped_and_sorted_fields.empty()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004703 mirror::ArtField* field = grouped_and_sorted_fields.front();
Brian Carlstromdbc05252011-09-09 01:59:59 -07004704 grouped_and_sorted_fields.pop_front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004705 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstromf3632832014-05-20 15:36:53 -07004706 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004707 fields->Set<false>(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004708 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004709 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004710 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07004711 ? sizeof(uint64_t)
4712 : sizeof(uint32_t)));
4713 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004714 }
4715
Elliott Hughesadb460d2011-10-05 17:02:34 -07004716 // 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 -07004717 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07004718 // We know there are no non-reference fields in the Reference classes, and we know
4719 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07004720 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004721 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07004722 --num_reference_fields;
4723 }
4724
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004725 if (kIsDebugBuild) {
4726 // Make sure that all reference fields appear before
4727 // non-reference fields, and all double-wide fields are aligned.
4728 bool seen_non_ref = false;
4729 for (size_t i = 0; i < num_fields; i++) {
4730 mirror::ArtField* field = fields->Get(i);
4731 if (false) { // enable to debug field layout
4732 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004733 << " class=" << PrettyClass(klass.Get())
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004734 << " field=" << PrettyField(field)
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07004735 << " offset="
4736 << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004737 }
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004738 Primitive::Type type = field->GetTypeAsPrimitiveType();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004739 bool is_primitive = type != Primitive::kPrimNot;
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004740 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004741 strcmp("referent", field->GetName()) == 0) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004742 is_primitive = true; // We lied above, so we have to expect a lie here.
4743 }
4744 if (is_primitive) {
4745 if (!seen_non_ref) {
4746 seen_non_ref = true;
Brian Carlstromf3632832014-05-20 15:36:53 -07004747 DCHECK_EQ(num_reference_fields, i) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004748 }
4749 } else {
Brian Carlstromf3632832014-05-20 15:36:53 -07004750 DCHECK(!seen_non_ref) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004751 }
4752 }
4753 if (!seen_non_ref) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004754 DCHECK_EQ(num_fields, num_reference_fields) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004755 }
4756 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004757
4758 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004759 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004760 if (is_static) {
4761 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004762 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004763 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004764 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004765 if (!klass->IsVariableSize()) {
Ian Rogerscb6b0f32014-08-12 02:30:58 -07004766 std::string temp;
4767 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07004768 size_t previous_size = klass->GetObjectSize();
4769 if (previous_size != 0) {
4770 // Make sure that we didn't originally have an incorrect size.
Ian Rogerscb6b0f32014-08-12 02:30:58 -07004771 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07004772 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004773 klass->SetObjectSize(size);
4774 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004775 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004776 return true;
4777}
4778
4779// Set the bitmap of reference offsets, refOffsets, from the ifields
4780// list.
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004781void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004782 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004783 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004784 if (super_class != NULL) {
4785 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07004786 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004787 if (reference_offsets == CLASS_WALK_SUPER) {
4788 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004789 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004790 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004791 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004792 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004793}
4794
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004795void ClassLinker::CreateReferenceStaticOffsets(Handle<mirror::Class> klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004796 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004797}
4798
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004799void ClassLinker::CreateReferenceOffsets(Handle<mirror::Class> klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004800 uint32_t reference_offsets) {
4801 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004802 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
4803 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogersef7d42f2014-01-06 12:55:46 -08004804 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004805 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07004806 // All of the fields that contain object references are guaranteed
4807 // to be at the beginning of the fields list.
4808 for (size_t i = 0; i < num_reference_fields; ++i) {
4809 // Note that byte_offset is the offset from the beginning of
4810 // object, not the offset into instance data
Ian Rogersef7d42f2014-01-06 12:55:46 -08004811 mirror::ArtField* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004812 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004813 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
4814 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
4815 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07004816 CHECK_NE(new_bit, 0U);
4817 reference_offsets |= new_bit;
4818 } else {
4819 reference_offsets = CLASS_WALK_SUPER;
4820 break;
4821 }
4822 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004823 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004824 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004825 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004826 } else {
4827 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004828 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004829}
4830
Mathieu Chartier590fee92013-09-13 13:46:47 -07004831mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004832 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004833 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004834 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004835 if (resolved != NULL) {
4836 return resolved;
4837 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07004838 uint32_t utf16_length;
4839 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004840 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004841 dex_cache->SetResolvedString(string_idx, string);
4842 return string;
4843}
4844
Mathieu Chartier590fee92013-09-13 13:46:47 -07004845mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08004846 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004847 StackHandleScope<2> hs(Thread::Current());
4848 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
4849 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07004850 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
4851}
4852
4853mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004854 Handle<mirror::DexCache> dex_cache,
4855 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004856 DCHECK(dex_cache.Get() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004857 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004858 if (resolved == NULL) {
Ian Rogers98379392014-02-24 16:53:16 -08004859 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07004860 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08004861 resolved = FindClass(self, descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004862 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05004863 // TODO: we used to throw here if resolved's class loader was not the
4864 // boot class loader. This was to permit different classes with the
4865 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004866 dex_cache->SetResolvedType(type_idx, resolved);
4867 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08004868 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08004869 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08004870 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004871 StackHandleScope<1> hs(self);
4872 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08004873 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004874 DCHECK(resolved == NULL); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08004875 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08004876 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004877 self->GetException(NULL)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08004878 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004879 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004880 }
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07004881 DCHECK((resolved == NULL) || resolved->IsResolved() || resolved->IsErroneous())
4882 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004883 return resolved;
4884}
4885
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004886mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
4887 Handle<mirror::DexCache> dex_cache,
4888 Handle<mirror::ClassLoader> class_loader,
4889 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07004890 InvokeType type) {
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004891 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07004892 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07004893 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004894 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004895 return resolved;
4896 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004897 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004898 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004899 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004900 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07004901 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004902 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004903 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004904 // Scan using method_idx, this saves string compares but will only hit for matching dex
4905 // caches/files.
4906 switch (type) {
4907 case kDirect: // Fall-through.
4908 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004909 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004910 break;
4911 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004912 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004913 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004914 break;
4915 case kSuper: // Fall-through.
4916 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004917 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004918 break;
4919 default:
4920 LOG(FATAL) << "Unreachable - invocation type: " << type;
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004921 }
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004922 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004923 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004924 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07004925 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07004926 switch (type) {
4927 case kDirect: // Fall-through.
4928 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08004929 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07004930 break;
4931 case kInterface:
4932 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004933 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004934 break;
4935 case kSuper: // Fall-through.
4936 case kVirtual:
4937 resolved = klass->FindVirtualMethod(name, signature);
4938 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004939 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004940 }
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004941 // If we found a method, check for incompatible class changes.
4942 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004943 // Be a good citizen and update the dex cache to speed subsequent calls.
4944 dex_cache->SetResolvedMethod(method_idx, resolved);
4945 return resolved;
4946 } else {
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004947 // If we had a method, it's an incompatible-class-change error.
4948 if (resolved != nullptr) {
4949 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
4950 } else {
4951 // We failed to find the method which means either an access error, an incompatible class
4952 // change, or no such method. First try to find the method among direct and virtual methods.
4953 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
4954 const Signature signature = dex_file.GetMethodSignature(method_id);
4955 switch (type) {
4956 case kDirect:
4957 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07004958 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004959 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
4960 // have had a resolved method before, which triggers the "true" branch above.
4961 break;
4962 case kInterface:
4963 case kVirtual:
4964 case kSuper:
4965 resolved = klass->FindDirectMethod(name, signature);
4966 break;
4967 }
4968
4969 // If we found something, check that it can be accessed by the referrer.
4970 if (resolved != nullptr && referrer.Get() != nullptr) {
4971 mirror::Class* methods_class = resolved->GetDeclaringClass();
4972 mirror::Class* referring_class = referrer->GetDeclaringClass();
4973 if (!referring_class->CanAccess(methods_class)) {
4974 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
4975 resolved, type);
4976 return nullptr;
4977 } else if (!referring_class->CanAccessMember(methods_class,
4978 resolved->GetAccessFlags())) {
4979 ThrowIllegalAccessErrorMethod(referring_class, resolved);
4980 return nullptr;
4981 }
4982 }
4983
4984 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
4985 // methods and throw if we find the method there. If we find nothing, throw a
4986 // NoSuchMethodError.
4987 switch (type) {
4988 case kDirect:
4989 case kStatic:
4990 if (resolved != nullptr) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004991 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07004992 } else {
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004993 resolved = klass->FindInterfaceMethod(name, signature);
4994 if (resolved != nullptr) {
4995 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
4996 } else {
4997 ThrowNoSuchMethodError(type, klass, name, signature);
4998 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004999 }
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005000 break;
5001 case kInterface:
5002 if (resolved != nullptr) {
5003 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005004 } else {
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005005 resolved = klass->FindVirtualMethod(name, signature);
5006 if (resolved != nullptr) {
5007 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5008 } else {
5009 ThrowNoSuchMethodError(type, klass, name, signature);
5010 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005011 }
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005012 break;
5013 case kSuper:
5014 ThrowNoSuchMethodError(type, klass, name, signature);
5015 break;
5016 case kVirtual:
5017 if (resolved != nullptr) {
5018 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5019 } else {
5020 resolved = klass->FindInterfaceMethod(name, signature);
5021 if (resolved != nullptr) {
5022 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5023 } else {
5024 ThrowNoSuchMethodError(type, klass, name, signature);
5025 }
5026 }
5027 break;
5028 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005029 }
5030 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005031 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005032 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005033}
5034
Mathieu Chartier590fee92013-09-13 13:46:47 -07005035mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005036 Handle<mirror::DexCache> dex_cache,
5037 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005038 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005039 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005040 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005041 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005042 return resolved;
5043 }
5044 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005045 Thread* const self = Thread::Current();
5046 StackHandleScope<1> hs(self);
5047 Handle<mirror::Class> klass(
5048 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005049 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005050 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005051 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005052 }
5053
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005054 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005055 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005056 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005057 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005058 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005059
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005060 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005061 const char* name = dex_file.GetFieldName(field_id);
5062 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5063 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005064 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005065 } else {
5066 resolved = klass->FindInstanceField(name, type);
5067 }
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005068 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005069 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005070 return NULL;
5071 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005072 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005073 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005074 return resolved;
5075}
5076
Brian Carlstromea46f952013-07-30 01:26:50 -07005077mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005078 uint32_t field_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005079 Handle<mirror::DexCache> dex_cache,
5080 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005081 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005082 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005083 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005084 return resolved;
5085 }
5086 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005087 Thread* self = Thread::Current();
5088 StackHandleScope<1> hs(self);
5089 Handle<mirror::Class> klass(
5090 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
5091 if (klass.Get() == NULL) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005092 DCHECK(Thread::Current()->IsExceptionPending());
5093 return NULL;
5094 }
5095
Ian Rogersdfb325e2013-10-30 01:00:44 -07005096 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5097 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005098 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005099 resolved = mirror::Class::FindField(self, klass, name, type);
Ian Rogersb067ac22011-12-13 18:05:09 -08005100 if (resolved != NULL) {
5101 dex_cache->SetResolvedField(field_idx, resolved);
5102 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005103 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005104 }
5105 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005106}
5107
Brian Carlstromea46f952013-07-30 01:26:50 -07005108const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005109 uint32_t* length) {
5110 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5111 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005112 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005113 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005114 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005115}
5116
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005117void ClassLinker::DumpAllClasses(int flags) {
5118 if (dex_cache_image_class_lookup_required_) {
5119 MoveImageClassesToClassTable();
5120 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005121 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5122 // 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 -08005123 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005124 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005125 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005126 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
5127 mirror::Class* klass = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07005128 all_classes.push_back(klass);
Ian Rogers5d76c432011-10-31 21:42:49 -07005129 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005130 }
5131
5132 for (size_t i = 0; i < all_classes.size(); ++i) {
5133 all_classes[i]->DumpClass(std::cerr, flags);
5134 }
5135}
5136
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005137void ClassLinker::DumpForSigQuit(std::ostream& os) {
5138 if (dex_cache_image_class_lookup_required_) {
5139 MoveImageClassesToClassTable();
5140 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005141 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005142 os << "Loaded classes: " << class_table_.size() << " allocated classes\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005143}
5144
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005145size_t ClassLinker::NumLoadedClasses() {
5146 if (dex_cache_image_class_lookup_required_) {
5147 MoveImageClassesToClassTable();
5148 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005149 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005150 return class_table_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005151}
5152
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005153pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005154 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005155}
5156
5157pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005158 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005159}
5160
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005161void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005162 DCHECK(!init_done_);
5163
5164 DCHECK(klass != NULL);
5165 DCHECK(klass->GetClassLoader() == NULL);
5166
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005167 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005168 DCHECK(class_roots != NULL);
5169 DCHECK(class_roots->Get(class_root) == NULL);
5170 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005171}
5172
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005173} // namespace art