blob: 99907e3161d21eac5958924c7a31101911f04b74 [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 Rogers22d5e732014-07-15 22:23:51 -070046#include "method_helper.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?
Mathieu Chartierf8322842014-05-16 10:59:25 -0700103 self->ThrowNewException(throw_location, c->GetVerifyErrorClass()->GetDescriptor().c_str(),
104 PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700105 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -0800106 self->ThrowNewException(throw_location, "Ljava/lang/NoClassDefFoundError;",
107 PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700108 }
109}
110
Ian Rogers62d6c772013-02-27 08:32:07 -0800111static void WrapExceptionInInitializer() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700112 Thread* self = Thread::Current();
113 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700114
115 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
116 CHECK(cause.get() != NULL);
117
118 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700119 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
120 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700121
Elliott Hughesa4f94742012-05-29 16:28:38 -0700122 // We only wrap non-Error exceptions; an Error can just be used as-is.
123 if (!is_error) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800124 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
125 self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;", NULL);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700126 }
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700127}
128
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800129static size_t Hash(const char* s) {
130 // This is the java.lang.String hashcode for convenience, not interoperability.
131 size_t hash = 0;
132 for (; *s != '\0'; ++s) {
133 hash = hash * 31 + *s;
134 }
135 return hash;
136}
137
Elliott Hughes418d20f2011-09-22 14:00:39 -0700138const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700139 "Ljava/lang/Class;",
140 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700141 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700142 "[Ljava/lang/Object;",
143 "Ljava/lang/String;",
Mathieu Chartier66f19252012-09-18 08:57:04 -0700144 "Ljava/lang/DexCache;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700145 "Ljava/lang/ref/Reference;",
Brian Carlstromea46f952013-07-30 01:26:50 -0700146 "Ljava/lang/reflect/ArtField;",
147 "Ljava/lang/reflect/ArtMethod;",
Ian Rogers466bb252011-10-14 03:29:56 -0700148 "Ljava/lang/reflect/Proxy;",
Mathieu Chartier66f19252012-09-18 08:57:04 -0700149 "[Ljava/lang/String;",
Brian Carlstromea46f952013-07-30 01:26:50 -0700150 "[Ljava/lang/reflect/ArtField;",
151 "[Ljava/lang/reflect/ArtMethod;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700152 "Ljava/lang/ClassLoader;",
Ian Rogers5167c972012-02-03 10:41:20 -0800153 "Ljava/lang/Throwable;",
jeffhao8cd6dda2012-02-22 10:15:34 -0800154 "Ljava/lang/ClassNotFoundException;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700155 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700156 "Z",
157 "B",
158 "C",
159 "D",
160 "F",
161 "I",
162 "J",
163 "S",
164 "V",
165 "[Z",
166 "[B",
167 "[C",
168 "[D",
169 "[F",
170 "[I",
171 "[J",
172 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700173 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700174};
175
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800176ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700177 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700178 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700179 dex_cache_image_class_lookup_required_(false),
180 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800181 class_roots_(nullptr),
182 array_iftable_(nullptr),
183 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700184 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800185 log_new_dex_caches_roots_(false),
186 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700187 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800188 portable_resolution_trampoline_(nullptr),
189 quick_resolution_trampoline_(nullptr),
190 portable_imt_conflict_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800191 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100192 quick_generic_jni_trampoline_(nullptr),
193 quick_to_interpreter_bridge_trampoline_(nullptr) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700194 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Ian Rogers98379392014-02-24 16:53:16 -0800195 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700196}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700197
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700198// To set a value for generic JNI. May be necessary in compiler tests.
199extern "C" void art_quick_generic_jni_trampoline(mirror::ArtMethod*);
200
Brian Carlstroma004aa92012-02-08 18:05:09 -0800201void ClassLinker::InitFromCompiler(const std::vector<const DexFile*>& boot_class_path) {
202 VLOG(startup) << "ClassLinker::Init";
203 CHECK(Runtime::Current()->IsCompiler());
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700204
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700205 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700206
Elliott Hughes30646832011-10-13 16:59:46 -0700207 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700208 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700209 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700210 // 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 -0800211 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700212 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
213 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700214 heap->AllocNonMovableObject<true>(self, nullptr,
215 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700216 VoidFunctor()))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700217 CHECK(java_lang_Class.Get() != NULL);
218 mirror::Class::SetClassClass(java_lang_Class.Get());
219 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700220 if (kUseBakerOrBrooksReadBarrier) {
221 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800222 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700223 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800224 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800225 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700226
Elliott Hughes418d20f2011-09-22 14:00:39 -0700227 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700228 Handle<mirror::Class> class_array_class(hs.NewHandle(
229 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700230 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700231
Ian Rogers23435d02012-09-24 11:23:12 -0700232 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700233 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
234 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700235 CHECK(java_lang_Object.Get() != NULL);
Ian Rogers23435d02012-09-24 11:23:12 -0700236 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700237 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700238 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700239
Ian Rogers23435d02012-09-24 11:23:12 -0700240 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700241 Handle<mirror::Class> object_array_class(hs.NewHandle(
242 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700243 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700244
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700245 // Setup the char (primitive) class to be used for char[].
246 Handle<mirror::Class> char_class(hs.NewHandle(
247 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700248
Ian Rogers23435d02012-09-24 11:23:12 -0700249 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700250 Handle<mirror::Class> char_array_class(hs.NewHandle(
251 AllocClass(self, java_lang_Class.Get(),
252 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700253 char_array_class->SetComponentType(char_class.Get());
254 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700255
Ian Rogers23435d02012-09-24 11:23:12 -0700256 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700257 Handle<mirror::Class> java_lang_String(hs.NewHandle(
258 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700259 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700260 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700261 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400262
Fred Shih4ee7a662014-07-11 09:59:27 -0700263 // Setup Reference.
264 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
265 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
266 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
267 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
268 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
269
Ian Rogers23435d02012-09-24 11:23:12 -0700270 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700271 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
272 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
273 kClassRootsMax));
274 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700275 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
276 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
277 SetClassRoot(kClassArrayClass, class_array_class.Get());
278 SetClassRoot(kObjectArrayClass, object_array_class.Get());
279 SetClassRoot(kCharArrayClass, char_array_class.Get());
280 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700281 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700282
283 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700284 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
285 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
286 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
287 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
288 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
289 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
290 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
291 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700292
Ian Rogers23435d02012-09-24 11:23:12 -0700293 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700294 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700295
Ian Rogers23435d02012-09-24 11:23:12 -0700296 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700297 Handle<mirror::Class> int_array_class(hs.NewHandle(
298 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700299 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700300 mirror::IntArray::SetArrayClass(int_array_class.Get());
301 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700302
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700303 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700304
Ian Rogers52813c92012-10-11 11:50:38 -0700305 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700306 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
307 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700308 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700309 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700310 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700311
Brian Carlstromf3632832014-05-20 15:36:53 -0700312 // Constructor, Field, Method, and AbstractMethod are necessary so
313 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700314 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
315 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700316 CHECK(java_lang_reflect_ArtField.Get() != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700317 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700318 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700319 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700320 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700321
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700322 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
323 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700324 CHECK(java_lang_reflect_ArtMethod.Get() != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700325 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700326 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700327 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700328
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700329 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700330
331 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700332 Handle<mirror::Class> object_array_string(hs.NewHandle(
333 AllocClass(self, java_lang_Class.Get(),
334 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700335 object_array_string->SetComponentType(java_lang_String.Get());
336 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700337
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700338 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
339 AllocClass(self, java_lang_Class.Get(),
340 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700341 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
342 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700343
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700344 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
345 AllocClass(self, java_lang_Class.Get(),
346 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700347 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
348 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700349
Ian Rogers23435d02012-09-24 11:23:12 -0700350 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
351 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
352 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700353 CHECK_NE(0U, boot_class_path.size());
354 for (size_t i = 0; i != boot_class_path.size(); ++i) {
355 const DexFile* dex_file = boot_class_path[i];
356 CHECK(dex_file != NULL);
357 AppendToBootClassPath(*dex_file);
358 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700359
360 // now we can use FindSystemClass
361
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700362 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700363 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
364 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700365
Jeff Hao88474b42013-10-23 16:24:40 -0700366 // Create runtime resolution and imt conflict methods. Also setup the default imt.
367 Runtime* runtime = Runtime::Current();
368 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
369 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
370 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
371
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700372 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
373 // we do not need friend classes or a publicly exposed setter.
374 quick_generic_jni_trampoline_ = reinterpret_cast<void*>(art_quick_generic_jni_trampoline);
375
Mathieu Chartier66f19252012-09-18 08:57:04 -0700376 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700377 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800378 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700379 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700380 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700381 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800382 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700383 std::ostringstream os1, os2;
384 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
385 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
386 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
387 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700388 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800389 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700390 CHECK_EQ(java_lang_String.Get(), String_class);
391 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700392 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700393
Ian Rogers23435d02012-09-24 11:23:12 -0700394 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800395 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800396 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700397
Ian Rogers98379392014-02-24 16:53:16 -0800398 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800399 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700400
Ian Rogers98379392014-02-24 16:53:16 -0800401 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700402 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700403
Ian Rogers98379392014-02-24 16:53:16 -0800404 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800405 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700406
Ian Rogers98379392014-02-24 16:53:16 -0800407 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700408 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700409
Ian Rogers98379392014-02-24 16:53:16 -0800410 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800411 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700412
Ian Rogers98379392014-02-24 16:53:16 -0800413 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800414 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700415
Ian Rogers98379392014-02-24 16:53:16 -0800416 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800417 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700418
Ian Rogers98379392014-02-24 16:53:16 -0800419 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700420 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700421
Ian Rogers98379392014-02-24 16:53:16 -0800422 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700423 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700424
Ian Rogers23435d02012-09-24 11:23:12 -0700425 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800426 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700427 CHECK(java_lang_Cloneable != NULL);
Ian Rogers98379392014-02-24 16:53:16 -0800428 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700429 CHECK(java_io_Serializable != NULL);
Ian Rogers23435d02012-09-24 11:23:12 -0700430 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
431 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700432 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700433 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700434 array_iftable->SetInterface(0, java_lang_Cloneable);
435 array_iftable->SetInterface(1, java_io_Serializable);
436 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700437
Ian Rogers23435d02012-09-24 11:23:12 -0700438 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700439 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
440 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
441 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
442 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700443 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700444 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800445 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700446 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700447
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700448 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800449 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700450 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700451
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700452 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800453 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700454 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700455
Brian Carlstromf3632832014-05-20 15:36:53 -0700456 mirror::Class* String_array_class =
457 FindSystemClass(self, class_roots_descriptors_[kJavaLangStringArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700458 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700459
Brian Carlstromea46f952013-07-30 01:26:50 -0700460 mirror::Class* Art_method_array_class =
Ian Rogers98379392014-02-24 16:53:16 -0800461 FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700462 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700463
Brian Carlstromea46f952013-07-30 01:26:50 -0700464 mirror::Class* Art_field_array_class =
Ian Rogers98379392014-02-24 16:53:16 -0800465 FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700466 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700467
Ian Rogers23435d02012-09-24 11:23:12 -0700468 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700469
Ian Rogers23435d02012-09-24 11:23:12 -0700470 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800471 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700472 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
473
Brian Carlstrom1f870082011-08-23 16:02:11 -0700474 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700475 // finish initializing Reference class
476 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
477 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
478 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
479 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
480 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700481 mirror::Class* java_lang_ref_FinalizerReference =
482 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700483 java_lang_ref_FinalizerReference->SetAccessFlags(
484 java_lang_ref_FinalizerReference->GetAccessFlags() |
485 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700486 mirror::Class* java_lang_ref_PhantomReference =
487 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700488 java_lang_ref_PhantomReference->SetAccessFlags(
489 java_lang_ref_PhantomReference->GetAccessFlags() |
490 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700491 mirror::Class* java_lang_ref_SoftReference =
492 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700493 java_lang_ref_SoftReference->SetAccessFlags(
494 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700495 mirror::Class* java_lang_ref_WeakReference =
496 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700497 java_lang_ref_WeakReference->SetAccessFlags(
498 java_lang_ref_WeakReference->GetAccessFlags() |
499 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700500
Ian Rogers23435d02012-09-24 11:23:12 -0700501 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800502 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700503 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700504 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
505
jeffhao8cd6dda2012-02-22 10:15:34 -0800506 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700507 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800508 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800509 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700510 SetClassRoot(kJavaLangClassNotFoundException,
511 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800512 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700513 SetClassRoot(kJavaLangStackTraceElementArrayClass,
514 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800515 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700516
Ian Rogers98379392014-02-24 16:53:16 -0800517 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700518
Brian Carlstroma004aa92012-02-08 18:05:09 -0800519 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700520}
521
Ian Rogers98379392014-02-24 16:53:16 -0800522void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800523 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700524
525 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700526 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700527 // as the types of the field can't be resolved prior to the runtime being
528 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800529 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700530 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800531 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800532
Brian Carlstromea46f952013-07-30 01:26:50 -0700533 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700534 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
535 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700536
Brian Carlstromea46f952013-07-30 01:26:50 -0700537 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700538 CHECK_STREQ(queue->GetName(), "queue");
539 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700540
Brian Carlstromea46f952013-07-30 01:26:50 -0700541 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700542 CHECK_STREQ(queueNext->GetName(), "queueNext");
543 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700544
Brian Carlstromea46f952013-07-30 01:26:50 -0700545 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700546 CHECK_STREQ(referent->GetName(), "referent");
547 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700548
Brian Carlstromea46f952013-07-30 01:26:50 -0700549 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700550 CHECK_STREQ(zombie->GetName(), "zombie");
551 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700552
Brian Carlstroma663ea52011-08-19 23:33:41 -0700553 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700554 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700555 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800556 mirror::Class* klass = GetClassRoot(class_root);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700557 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700558 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700559 // note SetClassRoot does additional validation.
560 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700561 }
562
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700563 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700564
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700565 // disable the slow paths in FindClass and CreatePrimitiveClass now
566 // that Object, Class, and Object[] are setup
567 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700568
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800569 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700570}
571
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700572void ClassLinker::RunRootClinits() {
573 Thread* self = Thread::Current();
574 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800575 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700576 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700577 StackHandleScope<1> hs(self);
578 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
579 EnsureInitialized(h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700580 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700581 }
582 }
583}
584
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700585bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800586 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000587 const char* oat_cache_filename,
588 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700589 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700590 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800591
Ian Rogers1d54e732013-05-02 21:10:01 -0700592 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800593 std::string boot_image_option("--boot-image=");
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700594 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800595
Brian Carlstrom6449c622014-02-10 23:48:36 -0800596 std::string dex_file_option("--dex-file=");
597 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800598
Brian Carlstrom6449c622014-02-10 23:48:36 -0800599 std::string oat_fd_option("--oat-fd=");
600 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800601
Brian Carlstrom6449c622014-02-10 23:48:36 -0800602 std::string oat_location_option("--oat-location=");
603 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800604
Brian Carlstrom6449c622014-02-10 23:48:36 -0800605 std::vector<std::string> argv;
606 argv.push_back(dex2oat);
607 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800608 argv.push_back("-classpath");
609 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800610 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800611
Ian Rogers8afeb852014-04-02 14:55:49 -0700612 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800613
Jeff Hao4a200f52014-04-01 14:58:49 -0700614 if (!Runtime::Current()->IsVerificationEnabled()) {
615 argv.push_back("--compiler-filter=verify-none");
616 }
617
Brian Carlstrom6449c622014-02-10 23:48:36 -0800618 if (!kIsTargetBuild) {
619 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700620 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700621
Brian Carlstrom6449c622014-02-10 23:48:36 -0800622 argv.push_back(boot_image_option);
623 argv.push_back(dex_file_option);
624 argv.push_back(oat_fd_option);
625 argv.push_back(oat_location_option);
626 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800627 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800628 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700629 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800630
631 return Exec(argv, error_msg);
jeffhao262bf462011-10-20 18:36:32 -0700632}
633
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700634const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700635 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800636 if (kIsDebugBuild) {
637 for (size_t i = 0; i < oat_files_.size(); ++i) {
638 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700639 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800640 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700641 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
642 oat_files_.push_back(oat_file);
643 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800644}
645
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700646OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
647 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700648 OatFile* oat_file = space->ReleaseOatFile();
649 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700650 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700651 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700652}
653
Brian Carlstromae826982011-11-09 01:33:42 -0800654const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800655 const char* dex_location = dex_file.GetLocation().c_str();
656 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700657 return FindOpenedOatFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800658}
659
Andreas Gampe833a4852014-05-21 18:46:59 -0700660const OatFile* ClassLinker::FindOpenedOatFile(const char* oat_location, const char* dex_location,
661 const uint32_t* const dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700662 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromae826982011-11-09 01:33:42 -0800663 for (size_t i = 0; i < oat_files_.size(); i++) {
664 const OatFile* oat_file = oat_files_[i];
665 DCHECK(oat_file != NULL);
Andreas Gampe833a4852014-05-21 18:46:59 -0700666
667 if (oat_location != nullptr) {
668 if (oat_file->GetLocation() != oat_location) {
669 continue;
670 }
671 }
672
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700673 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800674 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700675 false);
Brian Carlstroma004aa92012-02-08 18:05:09 -0800676 if (oat_dex_file != NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800677 return oat_file;
678 }
679 }
680 return NULL;
681}
682
Andreas Gampe833a4852014-05-21 18:46:59 -0700683static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file, const char* dex_location,
684 bool generated,
685 std::vector<std::string>* error_msgs,
686 std::vector<const DexFile*>* dex_files) {
687 if (oat_file == nullptr) {
688 return false;
689 }
690
691 size_t old_size = dex_files->size(); // To rollback on error.
692
693 bool success = true;
694 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100695 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700696 const char* next_name = next_name_str.c_str();
697
698 uint32_t dex_location_checksum;
699 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
700 std::string error_msg;
701 if (!DexFile::GetChecksum(next_name, dex_location_checksum_pointer, &error_msg)) {
702 DCHECK_EQ(false, i == 0 && generated);
703 dex_location_checksum_pointer = nullptr;
704 }
705
706 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
707
708 if (oat_dex_file == nullptr) {
709 if (i == 0 && generated) {
710 std::string error_msg;
711 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
712 " file'%s'", dex_location, dex_location_checksum,
713 oat_file->GetLocation().c_str());
714 error_msgs->push_back(error_msg);
715 }
716 break; // Not found, done.
717 }
718
719 // Checksum test. Test must succeed when generated.
720 success = !generated;
721 if (dex_location_checksum_pointer != nullptr) {
722 success = dex_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
723 }
724
725 if (success) {
726 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
727 if (dex_file == nullptr) {
728 success = false;
729 error_msgs->push_back(error_msg);
730 } else {
731 dex_files->push_back(dex_file);
732 }
733 }
734
735 // When we generated the file, we expect success, or something is terribly wrong.
736 CHECK_EQ(false, generated && !success)
737 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
738 << std::hex << " dex_location_checksum=" << dex_location_checksum
739 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
740 }
741
742 if (dex_files->size() == old_size) {
743 success = false; // We did not even find classes.dex
744 }
745
746 if (success) {
747 return true;
748 } else {
749 // Free all the dex files we have loaded.
750 auto it = dex_files->begin() + old_size;
751 auto it_end = dex_files->end();
752 for (; it != it_end; it++) {
753 delete *it;
754 }
755 dex_files->erase(dex_files->begin() + old_size, it_end);
756
757 return false;
758 }
759}
760
761// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
762// complicates the loading process, as we should not use an iterative loading process, because that
763// would register the oat file and dex files that come before the broken one. Instead, check all
764// multidex ahead of time.
765bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
766 std::vector<std::string>* error_msgs,
767 std::vector<const DexFile*>* dex_files) {
768 // 1) Check whether we have an open oat file.
769 // This requires a dex checksum, use the "primary" one.
770 uint32_t dex_location_checksum;
771 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
772 bool have_checksum = true;
773 std::string checksum_error_msg;
774 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
775 dex_location_checksum_pointer = nullptr;
776 have_checksum = false;
777 }
778
779 bool needs_registering = false;
780
781 std::unique_ptr<const OatFile> open_oat_file(FindOpenedOatFile(oat_location, dex_location,
782 dex_location_checksum_pointer));
783
784 // 2) If we do not have an open one, maybe there's one on disk already.
785
786 // In case the oat file is not open, we play a locking game here so
787 // that if two different processes race to load and register or generate
788 // (or worse, one tries to open a partial generated file) we will be okay.
789 // This is actually common with apps that use DexClassLoader to work
790 // around the dex method reference limit and that have a background
791 // service running in a separate process.
792 ScopedFlock scoped_flock;
793
794 if (open_oat_file.get() == nullptr) {
795 if (oat_location != nullptr) {
796 // Can only do this if we have a checksum, else error.
797 if (!have_checksum) {
798 error_msgs->push_back(checksum_error_msg);
799 return false;
800 }
801
802 std::string error_msg;
803
804 // We are loading or creating one in the future. Time to set up the file lock.
805 if (!scoped_flock.Init(oat_location, &error_msg)) {
806 error_msgs->push_back(error_msg);
807 return false;
808 }
809
Alex Lighta59dd802014-07-02 16:28:08 -0700810 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700811 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
812 oat_location, &error_msg));
813
814 if (open_oat_file.get() == nullptr) {
815 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
816 dex_location, oat_location, error_msg.c_str());
817 VLOG(class_linker) << compound_msg;
818 error_msgs->push_back(compound_msg);
819 }
820 } else {
821 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100822 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700823 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
824 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100825 kRuntimeISA, error_msgs,
826 &obsolete_file_cleanup_failed));
827 // There's no point in going forward and eventually try to regenerate the
828 // file if we couldn't remove the obsolete one. Mostly likely we will fail
829 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100830 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
831 if (obsolete_file_cleanup_failed) {
832 return false;
833 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700834 }
835 needs_registering = true;
836 }
837
838 // 3) If we have an oat file, check all contained multidex files for our dex_location.
839 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
840 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location, false, error_msgs,
841 dex_files);
842 if (success) {
843 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
844 if (needs_registering) {
845 // We opened the oat file, so we must register it.
846 RegisterOatFile(oat_file);
847 }
848 return true;
849 } else {
850 if (needs_registering) {
851 // We opened it, delete it.
852 open_oat_file.reset();
853 } else {
854 open_oat_file.release(); // Do not delete open oat files.
855 }
856 }
857
858 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
859
860 // Need a checksum, fail else.
861 if (!have_checksum) {
862 error_msgs->push_back(checksum_error_msg);
863 return false;
864 }
865
866 // Look in cache location if no oat_location is given.
867 std::string cache_location;
868 if (oat_location == nullptr) {
869 // Use the dalvik cache.
870 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
871 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
872 oat_location = cache_location.c_str();
873 }
874
875 // Definitely need to lock now.
876 if (!scoped_flock.HasFile()) {
877 std::string error_msg;
878 if (!scoped_flock.Init(oat_location, &error_msg)) {
879 error_msgs->push_back(error_msg);
880 return false;
881 }
882 }
883
884 // Create the oat file.
885 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
886 oat_location, error_msgs));
887
888 // Failed, bail.
889 if (open_oat_file.get() == nullptr) {
890 return false;
891 }
892
893 // Try to load again, but stronger checks.
894 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location, true, error_msgs,
895 dex_files);
896 if (success) {
897 RegisterOatFile(open_oat_file.release());
898 return true;
899 } else {
900 return false;
901 }
902}
903
904const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
905 uint32_t dex_location_checksum,
906 const char* oat_location,
907 std::string* error_msg) {
Ian Rogers700a4022014-05-19 16:49:03 -0700908 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, NULL,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700909 !Runtime::Current()->IsCompiler(),
910 error_msg));
911 if (oat_file.get() == nullptr) {
912 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
913 error_msg->c_str());
914 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800915 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700916 Runtime* runtime = Runtime::Current();
917 const ImageHeader& image_header = runtime->GetHeap()->GetImageSpace()->GetImageHeader();
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700918 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
919 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
920 if (expected_image_oat_checksum != actual_image_oat_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700921 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
922 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
923 actual_image_oat_checksum);
924 return nullptr;
Brian Carlstrom28db0122012-10-18 16:20:41 -0700925 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700926
Ian Rogersef7d42f2014-01-06 12:55:46 -0800927 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700928 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
929 if (expected_image_oat_offset != actual_image_oat_offset) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800930 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
931 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700932 actual_image_oat_offset);
933 return nullptr;
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700934 }
Alex Lighta59dd802014-07-02 16:28:08 -0700935 int32_t expected_patch_delta = image_header.GetPatchDelta();
936 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
937 if (expected_patch_delta != actual_patch_delta) {
938 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
939 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
940 return nullptr;
941 }
Vladimir Marko64e7ac02014-05-01 15:43:47 +0100942 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
943 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700944 if (oat_dex_file == nullptr) {
945 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
946 dex_location);
947 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800948 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700949 uint32_t expected_dex_checksum = dex_location_checksum;
950 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
951 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700952 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
953 "found 0x%x", oat_location, expected_dex_checksum,
954 actual_dex_checksum);
955 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800956 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700957 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
958 if (dex_file.get() != nullptr) {
959 return oat_file.release();
960 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700961 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700962 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700963}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700964
Andreas Gampe833a4852014-05-21 18:46:59 -0700965const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
966 int fd, const char* oat_location,
967 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800968 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700969 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -0700970 std::string error_msg;
971 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -0700972 CHECK(!error_msg.empty());
973 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700974 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800975 }
Ian Rogers700a4022014-05-19 16:49:03 -0700976 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, NULL,
Vladimir Marko64e7ac02014-05-01 15:43:47 +0100977 !Runtime::Current()->IsCompiler(),
978 &error_msg));
979 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700980 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
981 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -0700982 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700983 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800984 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700985
986 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800987}
988
Brian Carlstromafe25512012-06-27 17:02:58 -0700989bool ClassLinker::VerifyOatFileChecksums(const OatFile* oat_file,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700990 const char* dex_location,
991 uint32_t dex_location_checksum,
Narayan Kamath52f84882014-05-02 10:10:39 +0100992 const InstructionSet instruction_set,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700993 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -0700994 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +0100995 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
996
997 // If the requested instruction set is the same as the current runtime,
998 // we can use the checksums directly. If it isn't, we'll have to read the
999 // image header from the image for the right instruction set.
1000 uint32_t image_oat_checksum = 0;
1001 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001002 int32_t image_patch_delta = 0;
1003 if (instruction_set == Runtime::Current()->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001004 const ImageHeader& image_header = image_space->GetImageHeader();
1005 image_oat_checksum = image_header.GetOatChecksum();
1006 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001007 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001008 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001009 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001010 image_space->GetImageLocation().c_str(), instruction_set));
1011 image_oat_checksum = image_header->GetOatChecksum();
1012 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001013 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001014 }
1015 const OatHeader& oat_header = oat_file->GetOatHeader();
1016 bool image_check = ((oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum)
Alex Lighta59dd802014-07-02 16:28:08 -07001017 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin)
1018 && (oat_header.GetImagePatchDelta() == image_patch_delta));
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001019
Brian Carlstromf3632832014-05-20 15:36:53 -07001020 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1021 &dex_location_checksum);
Brian Carlstromafe25512012-06-27 17:02:58 -07001022 if (oat_dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001023 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1024 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Brian Carlstromafe25512012-06-27 17:02:58 -07001025 std::vector<const OatFile::OatDexFile*> oat_dex_files = oat_file->GetOatDexFiles();
1026 for (size_t i = 0; i < oat_dex_files.size(); i++) {
1027 const OatFile::OatDexFile* oat_dex_file = oat_dex_files[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001028 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s'",
1029 oat_file->GetLocation().c_str(),
1030 oat_dex_file->GetDexFileLocation().c_str());
Brian Carlstromafe25512012-06-27 17:02:58 -07001031 }
1032 return false;
1033 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001034 bool dex_check = dex_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001035
Brian Carlstromafe25512012-06-27 17:02:58 -07001036 if (image_check && dex_check) {
1037 return true;
1038 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001039
Brian Carlstromafe25512012-06-27 17:02:58 -07001040 if (!image_check) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001041 ScopedObjectAccess soa(Thread::Current());
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +00001042 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d) with (0x%x, %" PRIdPTR ")",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001043 oat_file->GetLocation().c_str(),
1044 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1045 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +00001046 image_oat_checksum, image_oat_data_begin);
Brian Carlstromafe25512012-06-27 17:02:58 -07001047 }
1048 if (!dex_check) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001049 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x) with '%s' (0x%x)",
1050 oat_file->GetLocation().c_str(),
1051 oat_dex_file->GetDexFileLocationChecksum(),
1052 dex_location, dex_location_checksum);
Brian Carlstromafe25512012-06-27 17:02:58 -07001053 }
1054 return false;
1055}
1056
Alex Lighta59dd802014-07-02 16:28:08 -07001057bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1058 const char* dex_location,
1059 std::string* error_msg) {
1060 CHECK(oat_file != nullptr);
1061 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001062 std::unique_ptr<const DexFile> dex_file;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001063 uint32_t dex_location_checksum;
1064 if (!DexFile::GetChecksum(dex_location, &dex_location_checksum, error_msg)) {
1065 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1066 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1067 // directory.
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001068 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, NULL);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001069 if (oat_dex_file == nullptr) {
1070 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001071 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001072 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001073 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001074 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001075 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001076 } else {
Alex Lighta59dd802014-07-02 16:28:08 -07001077 bool verified = VerifyOatFileChecksums(oat_file, dex_location, dex_location_checksum,
Narayan Kamath52f84882014-05-02 10:10:39 +01001078 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001079 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001080 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001081 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001082 dex_file.reset(oat_file->GetOatDexFile(dex_location,
1083 &dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001084 }
Alex Lighta59dd802014-07-02 16:28:08 -07001085 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001086}
1087
Andreas Gampe833a4852014-05-21 18:46:59 -07001088const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001089 const char* dex_location,
1090 const uint32_t* const dex_location_checksum,
1091 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001092 std::vector<std::string>* error_msgs,
1093 bool* obsolete_file_cleanup_failed) {
1094 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001095 bool already_opened = false;
1096 std::string dex_location_str(dex_location);
1097 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1098 &already_opened,
1099 obsolete_file_cleanup_failed,
1100 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001101 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001102 if (oat_file.get() == nullptr) {
1103 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1104 dex_location));
1105 return nullptr;
1106 } else if (!VerifyOatWithDexFile(oat_file.get(), dex_location, &error_msg)) {
1107 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1108 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001109 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001110 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001111 } else {
1112 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001113 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001114}
1115
Brian Carlstromae826982011-11-09 01:33:42 -08001116const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001117 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001118 for (size_t i = 0; i < oat_files_.size(); i++) {
1119 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001120 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001121 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001122 return oat_file;
1123 }
1124 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001125 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001126}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001127
Alex Lighta59dd802014-07-02 16:28:08 -07001128const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1129 InstructionSet isa,
1130 bool *already_opened,
1131 bool *obsolete_file_cleanup_failed,
1132 std::vector<std::string>* error_msgs) {
1133 // Find out if we've already opened the file
1134 const OatFile* ret = nullptr;
1135 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1136 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1137 if (ret != nullptr) {
1138 *already_opened = true;
1139 return ret;
1140 }
1141
1142 std::string dalvik_cache;
1143 bool have_android_data = false;
1144 bool have_dalvik_cache = false;
1145 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
1146 &have_android_data, &have_dalvik_cache);
1147 std::string cache_filename;
1148 if (have_dalvik_cache) {
1149 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1150 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1151 if (ret != nullptr) {
1152 *already_opened = true;
1153 return ret;
1154 }
1155 } else {
1156 // If we need to relocate we should just place odex back where it started.
1157 cache_filename = odex_filename;
1158 }
1159
1160 ret = nullptr;
1161
1162 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1163 //
1164 // Now we do the following:
1165 // 1) Try and open the odex version
1166 // 2) If present, checksum-verified & relocated correctly return it
1167 // 3) Close the odex version to free up its address space.
1168 // 4) Try and open the cache version
1169 // 5) If present, checksum-verified & relocated correctly return it
1170 // 6) Close the cache version to free up its address space.
1171 // 7) If we should relocate:
1172 // a) If we have opened and checksum-verified the odex version relocate it to
1173 // 'cache_filename' and return it
1174 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1175 // it. This should not happen often (I think only the run-test's will hit this case).
1176 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1177 // this point.
1178 // 9) Return nullptr
1179
1180 *already_opened = false;
1181 const Runtime* runtime = Runtime::Current();
1182 CHECK(runtime != nullptr);
1183 bool executable = !runtime->IsCompiler();
1184
1185 std::string odex_error_msg;
1186 bool should_patch_system = false;
1187 bool odex_checksum_verified = false;
1188 {
1189 // There is a high probability that these both these oat files map similar/the same address
1190 // spaces so we must scope them like this so they each gets its turn.
1191 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, NULL,
1192 executable, &odex_error_msg));
1193 if (odex_oat_file.get() != nullptr && CheckOatFile(odex_oat_file.get(), isa,
1194 &odex_checksum_verified,
1195 &odex_error_msg)) {
1196 error_msgs->push_back(odex_error_msg);
1197 return odex_oat_file.release();
1198 } else if (odex_checksum_verified) {
1199 // We can just relocate
1200 should_patch_system = true;
1201 odex_error_msg = "Image Patches are incorrect";
1202 }
1203 }
1204
1205
1206 std::string cache_error_msg;
1207 bool should_patch_cache = false;
1208 bool cache_checksum_verified = false;
1209 if (have_dalvik_cache) {
1210 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, NULL,
1211 executable, &cache_error_msg));
1212 if (cache_oat_file.get() != nullptr && CheckOatFile(cache_oat_file.get(), isa,
1213 &cache_checksum_verified,
1214 &cache_error_msg)) {
1215 error_msgs->push_back(cache_error_msg);
1216 return cache_oat_file.release();
1217 } else if (cache_checksum_verified) {
1218 // We can just relocate
1219 should_patch_cache = true;
1220 cache_error_msg = "Image Patches are incorrect";
1221 }
1222 } else if (have_android_data) {
1223 // dalvik_cache does not exist but android data does. This means we should be able to create
1224 // it, so we should try.
1225 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1226 }
1227
1228 ret = nullptr;
1229 std::string error_msg;
1230 if (runtime->CanRelocate()) {
1231 // Run relocation
1232 const std::string& image_location =
1233 Runtime::Current()->GetHeap()->GetImageSpace()->GetImageLocation();
1234 if (odex_checksum_verified && should_patch_system) {
1235 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1236 } else if (cache_checksum_verified && should_patch_cache) {
1237 CHECK(have_dalvik_cache);
1238 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1239 }
1240 }
1241 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1242 // implicitly: were able to fine where the cached version is but we were unable to use it,
1243 // either as a destination for relocation or to open a file. We should delete it if it is
1244 // there.
1245 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1246 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1247 "searching for dex file %s: %s",
1248 cache_filename.c_str(), dex_location.c_str(),
1249 strerror(errno));
1250 error_msgs->push_back(rm_error_msg);
1251 VLOG(class_linker) << rm_error_msg;
1252 // Let the caller know that we couldn't remove the obsolete file.
1253 // This is a good indication that further writes may fail as well.
1254 *obsolete_file_cleanup_failed = true;
1255 }
1256 }
1257 if (ret == nullptr) {
1258 VLOG(class_linker) << error_msg;
1259 error_msgs->push_back(error_msg);
1260 std::string relocation_msg;
1261 if (runtime->CanRelocate()) {
1262 relocation_msg = StringPrintf(" and relocation failed");
1263 }
1264 if (have_dalvik_cache && cache_checksum_verified) {
1265 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1266 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1267 cache_filename.c_str(), cache_error_msg.c_str(),
1268 relocation_msg.c_str());
1269 } else {
1270 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1271 "dalvik_cache availible)%s.", odex_filename.c_str(),
1272 odex_error_msg.c_str(), relocation_msg.c_str());
1273 }
1274 VLOG(class_linker) << error_msg;
1275 error_msgs->push_back(error_msg);
1276 }
1277 return ret;
1278}
1279
1280const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1281 const std::string& output_oat,
1282 const std::string& image_location,
1283 InstructionSet isa,
1284 std::string* error_msg) {
1285 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
1286 std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
1287
1288 std::string isa_arg("--instruction-set=");
1289 isa_arg += GetInstructionSetString(isa);
1290 std::string input_oat_filename_arg("--input-oat-file=");
1291 input_oat_filename_arg += input_oat;
1292 std::string output_oat_filename_arg("--output-oat-file=");
1293 output_oat_filename_arg += output_oat;
1294 std::string patched_image_arg("--patched-image-location=");
1295 patched_image_arg += image_location;
1296
1297 std::vector<std::string> argv;
1298 argv.push_back(patchoat);
1299 argv.push_back(isa_arg);
1300 argv.push_back(input_oat_filename_arg);
1301 argv.push_back(output_oat_filename_arg);
1302 argv.push_back(patched_image_arg);
1303
1304 std::string command_line(Join(argv, ' '));
1305 LOG(INFO) << "Relocate Oat File: " << command_line;
1306 bool success = Exec(argv, error_msg);
1307 if (success) {
1308 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, NULL,
1309 !Runtime::Current()->IsCompiler(), error_msg));
1310 bool checksum_verified = false;
1311 if (output.get() != nullptr && CheckOatFile(output.get(), isa, &checksum_verified, error_msg)) {
1312 return output.release();
1313 } else if (output.get() != nullptr) {
1314 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1315 "but output file '%s' failed verifcation: %s",
1316 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1317 } else {
1318 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1319 "but was unable to open output file '%s': %s",
1320 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1321 }
1322 } else {
1323 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1324 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1325 error_msg->c_str());
1326 }
1327 return nullptr;
1328}
1329
1330int32_t ClassLinker::GetRequiredDelta(const OatFile* oat_file, InstructionSet isa) {
1331 Runtime* runtime = Runtime::Current();
1332 int32_t real_patch_delta;
1333 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1334 if (isa == Runtime::Current()->GetInstructionSet()) {
1335 const ImageHeader& image_header = image_space->GetImageHeader();
1336 real_patch_delta = image_header.GetPatchDelta();
1337 } else {
1338 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1339 image_space->GetImageLocation().c_str(), isa));
1340 real_patch_delta = image_header->GetPatchDelta();
1341 }
1342 const OatHeader& oat_header = oat_file->GetOatHeader();
1343 return real_patch_delta - oat_header.GetImagePatchDelta();
1344}
1345
1346bool ClassLinker::CheckOatFile(const OatFile* oat_file, InstructionSet isa,
1347 bool* checksum_verified,
1348 std::string* error_msg) {
1349 std::string compound_msg("Oat file failed to verify: ");
1350 Runtime* runtime = Runtime::Current();
1351 uint32_t real_image_checksum;
1352 void* real_image_oat_offset;
1353 int32_t real_patch_delta;
1354 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1355 if (isa == Runtime::Current()->GetInstructionSet()) {
1356 const ImageHeader& image_header = image_space->GetImageHeader();
1357 real_image_checksum = image_header.GetOatChecksum();
1358 real_image_oat_offset = image_header.GetOatDataBegin();
1359 real_patch_delta = image_header.GetPatchDelta();
1360 } else {
1361 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1362 image_space->GetImageLocation().c_str(), isa));
1363 real_image_checksum = image_header->GetOatChecksum();
1364 real_image_oat_offset = image_header->GetOatDataBegin();
1365 real_patch_delta = image_header->GetPatchDelta();
1366 }
1367
1368 const OatHeader& oat_header = oat_file->GetOatHeader();
1369
1370 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1371 *checksum_verified = oat_image_checksum == real_image_checksum;
1372 if (!*checksum_verified) {
1373 compound_msg += StringPrintf(" Oat Image Checksum Incorrect (expected 0x%x, recieved 0x%x)",
1374 real_image_checksum, oat_image_checksum);
1375 }
1376
1377 void* oat_image_oat_offset =
1378 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1379 bool offset_verified = oat_image_oat_offset == real_image_oat_offset;
1380 if (!offset_verified) {
1381 compound_msg += StringPrintf(" Oat Image oat offset incorrect (expected 0x%p, recieved 0x%p)",
1382 real_image_oat_offset, oat_image_oat_offset);
1383 }
1384
1385 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1386 bool patch_delta_verified = oat_patch_delta == real_patch_delta;
1387 if (!patch_delta_verified) {
1388 compound_msg += StringPrintf(" Oat image patch delta incorrect (expected 0x%x, recieved 0x%x)",
1389 real_patch_delta, oat_patch_delta);
1390 }
1391
1392 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
1393 if (ret) {
1394 *error_msg = compound_msg;
1395 }
1396 return ret;
1397}
1398
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001399const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1400 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001401 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001402 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001403 return oat_file;
1404 }
1405
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001406 oat_file = OatFile::Open(oat_location, oat_location, NULL, !Runtime::Current()->IsCompiler(),
1407 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001408 if (oat_file == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -08001409 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001410 }
1411 return oat_file;
1412}
1413
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001414static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
Ian Rogers848871b2013-08-05 10:56:33 -07001415 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001416 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1417
Ian Rogers848871b2013-08-05 10:56:33 -07001418 DCHECK(obj != NULL);
1419 DCHECK(class_linker != NULL);
1420
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001421 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001422 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001423 if (!method->IsNative()) {
1424 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
1425 if (method != Runtime::Current()->GetResolutionMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001426 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1427 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers848871b2013-08-05 10:56:33 -07001428 }
1429 }
1430 }
1431}
1432
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001433void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001434 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001435 CHECK(!init_done_);
1436
Mathieu Chartier590fee92013-09-13 13:46:47 -07001437 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001438 gc::Heap* heap = Runtime::Current()->GetHeap();
1439 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001440 dex_cache_image_class_lookup_required_ = true;
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001441 CHECK(space != NULL);
1442 OatFile& oat_file = GetImageOatFile(space);
1443 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1444 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001445 const char* image_file_location = oat_file.GetOatHeader().
1446 GetStoreValueByKey(OatHeader::kImageLocationKey);
1447 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001448 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1449 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001450 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1451 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001452 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001453 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001454 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1455 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1456 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001457
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001458 StackHandleScope<1> hs(self);
1459 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1460 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1461 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001462 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001463
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001464 // Special case of setting up the String class early so that we can test arbitrary objects
1465 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001466 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001467
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001468 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001469 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001470 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001471 StackHandleScope<1> hs(self);
1472 Handle<mirror::DexCache> dex_cache(hs.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001473 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001474 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1475 nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001476 CHECK(oat_dex_file != NULL) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001477 std::string error_msg;
1478 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001479 if (dex_file == NULL) {
1480 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001481 << " from within oat file " << oat_file.GetLocation()
1482 << " error '" << error_msg << "'";
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001483 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001484
1485 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1486
1487 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001488 }
1489
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001490 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1491 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001492 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001493
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001494 // Set entry point to interpreter if in InterpretOnly mode.
1495 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001496 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001497 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001498 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001499
1500 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001501 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001502 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001503
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001504 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001505 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
1506 DCHECK(array_iftable_.Read() == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001507 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001508 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001509 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001510 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1511 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1512 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1513 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1514 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1515 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1516 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1517 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1518 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1519 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001520
Ian Rogers98379392014-02-24 16:53:16 -08001521 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001522
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001523 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001524}
1525
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001526void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1527 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1528 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001529 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1530 it.second.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001531 }
1532 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1533 for (auto& pair : new_class_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001534 mirror::Class* old_ref = pair.second.Read<kWithoutReadBarrier>();
1535 pair.second.VisitRoot(callback, arg, 0, kRootStickyClass);
1536 mirror::Class* new_ref = pair.second.Read<kWithoutReadBarrier>();
1537 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001538 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1539 // corresponding object. This is slow, but luckily for us, this may only happen with a
1540 // concurrent moving GC.
1541 for (auto it = class_table_.lower_bound(pair.first), end = class_table_.end();
1542 it != end && it->first == pair.first; ++it) {
1543 // If the class stored matches the old class, update it to the new value.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001544 if (old_ref == it->second.Read<kWithoutReadBarrier>()) {
1545 it->second = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001546 }
1547 }
1548 }
1549 }
1550 }
1551 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1552 new_class_roots_.clear();
1553 }
1554 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1555 log_new_class_table_roots_ = true;
1556 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1557 log_new_class_table_roots_ = false;
1558 }
1559 // We deliberately ignore the class roots in the image since we
1560 // handle image roots by using the MS/CMS rescanning of dirty cards.
1561}
1562
Brian Carlstroma663ea52011-08-19 23:33:41 -07001563// Keep in sync with InitCallback. Anything we visit, we need to
1564// reinit references to when reinitializing a ClassLinker from a
1565// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001566void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001567 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001568 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001569 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001570 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001571 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001572 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1573 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001574 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001575 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1576 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001577 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001578 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001579 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001580 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1581 new_dex_cache_roots_.clear();
1582 }
1583 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1584 log_new_dex_caches_roots_ = true;
1585 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1586 log_new_dex_caches_roots_ = false;
1587 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001588 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001589 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001590 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1591 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001592 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001593 if (!find_array_class_cache_[i].IsNull()) {
1594 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001595 }
1596 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001597}
1598
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001599void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1600 if (dex_cache_image_class_lookup_required_) {
1601 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001602 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001603 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001604 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1605 mirror::Class* c = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07001606 if (!visitor(c, arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001607 return;
1608 }
1609 }
1610}
1611
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001612static bool GetClassesVisitor(mirror::Class* c, void* arg) {
1613 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001614 classes->insert(c);
1615 return true;
1616}
1617
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001618void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001619 std::set<mirror::Class*> classes;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001620 VisitClasses(GetClassesVisitor, &classes);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001621 for (mirror::Class* klass : classes) {
1622 if (!visitor(klass, arg)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001623 return;
1624 }
1625 }
1626}
1627
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001628ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001629 mirror::Class::ResetClass();
1630 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001631 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001632 mirror::ArtField::ResetClass();
1633 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001634 mirror::BooleanArray::ResetArrayClass();
1635 mirror::ByteArray::ResetArrayClass();
1636 mirror::CharArray::ResetArrayClass();
1637 mirror::DoubleArray::ResetArrayClass();
1638 mirror::FloatArray::ResetArrayClass();
1639 mirror::IntArray::ResetArrayClass();
1640 mirror::LongArray::ResetArrayClass();
1641 mirror::ShortArray::ResetArrayClass();
1642 mirror::Throwable::ResetClass();
1643 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001644 STLDeleteElements(&boot_class_path_);
1645 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001646}
1647
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001648mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001649 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001650 StackHandleScope<16> hs(self);
1651 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1652 Handle<mirror::DexCache> dex_cache(
1653 hs.NewHandle(down_cast<mirror::DexCache*>(
1654 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1655 VoidFunctor()))));
1656 if (dex_cache.Get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001657 return NULL;
1658 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001659 Handle<mirror::String>
1660 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
1661 if (location.Get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001662 return NULL;
1663 }
Ian Rogers700a4022014-05-19 16:49:03 -07001664 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001665 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
1666 if (strings.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001667 return NULL;
1668 }
Ian Rogers700a4022014-05-19 16:49:03 -07001669 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001670 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
1671 if (types.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001672 return NULL;
1673 }
Ian Rogers700a4022014-05-19 16:49:03 -07001674 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001675 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
1676 if (methods.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001677 return NULL;
1678 }
Ian Rogers700a4022014-05-19 16:49:03 -07001679 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001680 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
1681 if (fields.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001682 return NULL;
1683 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001684 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1685 fields.Get());
1686 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001687}
1688
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001689mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001690 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001691 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001692 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001693 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001694 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001695 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1696 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001697 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001698 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001699 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001700 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001701 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001702}
1703
Ian Rogers6fac4472014-02-25 17:01:10 -08001704mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001705 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001706}
1707
Brian Carlstromea46f952013-07-30 01:26:50 -07001708mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001709 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001710 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001711}
1712
Brian Carlstromea46f952013-07-30 01:26:50 -07001713mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001714 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001715 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001716}
1717
Mathieu Chartier590fee92013-09-13 13:46:47 -07001718mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1719 Thread* self, size_t length) {
1720 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1721 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001722}
1723
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001724mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1725 mirror::Class* klass) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001726 DCHECK(klass != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001727
1728 // For temporary classes we must wait for them to be retired.
1729 if (init_done_ && klass->IsTemp()) {
1730 CHECK(!klass->IsResolved());
1731 if (klass->IsErroneous()) {
1732 ThrowEarlierClassFailure(klass);
1733 return nullptr;
1734 }
1735 StackHandleScope<1> hs(self);
1736 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1737 ObjectLock<mirror::Class> lock(self, h_class);
1738 // Loop and wait for the resolving thread to retire this class.
1739 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1740 lock.WaitIgnoringInterrupts();
1741 }
1742 if (h_class->IsErroneous()) {
1743 ThrowEarlierClassFailure(h_class.Get());
1744 return nullptr;
1745 }
1746 CHECK(h_class->IsRetired());
1747 // Get the updated class from class table.
1748 klass = LookupClass(descriptor, h_class.Get()->GetClassLoader());
1749 }
1750
Brian Carlstromaded5f72011-10-07 17:15:04 -07001751 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001752 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001753 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001754 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
1755 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001756 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001757 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
1758 ThrowClassCircularityError(h_class.Get());
1759 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001760 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001761 }
1762 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001763 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08001764 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001765 }
1766 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001767
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001768 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001769 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001770 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001771 }
1772 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001773 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08001774 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001775 return klass;
1776}
1777
Ian Rogers98379392014-02-24 16:53:16 -08001778mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07001779 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001780 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08001781 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001782 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001783 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001784 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1785 // for primitive classes that aren't backed by dex files.
1786 return FindPrimitiveClass(descriptor[0]);
1787 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001788 // Find the class in the loaded classes table.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001789 mirror::Class* klass = LookupClass(descriptor, class_loader.Get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001790 if (klass != NULL) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001791 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001792 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001793 // Class is not yet loaded.
1794 if (descriptor[0] == '[') {
Ian Rogers98379392014-02-24 16:53:16 -08001795 return CreateArrayClass(self, descriptor, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001796 } else if (class_loader.Get() == nullptr) {
Jesse Wilson47daf872011-11-23 11:42:45 -05001797 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1798 if (pair.second != NULL) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001799 StackHandleScope<1> hs(self);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07001800 return DefineClass(descriptor, NullHandle<mirror::ClassLoader>(), *pair.first, *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05001801 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001802 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogersbe7149f2013-08-20 09:29:39 -07001803 // First try the boot class path, we check the descriptor first to avoid an unnecessary
1804 // throw of a NoClassDefFoundError.
1805 if (IsInBootClassPath(descriptor)) {
Ian Rogers98379392014-02-24 16:53:16 -08001806 mirror::Class* system_class = FindSystemClass(self, descriptor);
Ian Rogersbe7149f2013-08-20 09:29:39 -07001807 CHECK(system_class != NULL);
Jesse Wilson47daf872011-11-23 11:42:45 -05001808 return system_class;
1809 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07001810 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001811 const std::vector<const DexFile*>* class_path;
1812 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07001813 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001814 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001815 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001816 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
1817 }
1818
1819 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, *class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001820 if (pair.second != NULL) {
1821 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001822 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001823
1824 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001825 ScopedObjectAccessUnchecked soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001826 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001827 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08001828 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001829 ScopedLocalRef<jobject> result(soa.Env(), NULL);
Ian Rogers365c1022012-06-22 15:05:28 -07001830 {
1831 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001832 ScopedLocalRef<jobject> class_name_object(soa.Env(),
1833 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers365c1022012-06-22 15:05:28 -07001834 if (class_name_object.get() == NULL) {
1835 return NULL;
1836 }
1837 CHECK(class_loader_object.get() != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001838 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
1839 WellKnownClasses::java_lang_ClassLoader_loadClass,
1840 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05001841 }
Ian Rogers98379392014-02-24 16:53:16 -08001842 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001843 // If the ClassLoader threw, pass that exception up.
1844 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001845 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001846 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers62d6c772013-02-27 08:32:07 -08001847 ThrowNullPointerException(NULL, StringPrintf("ClassLoader.loadClass returned null for %s",
1848 class_name_string.c_str()).c_str());
Ian Rogerscab01012012-01-10 17:35:46 -08001849 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001850 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001851 // success, return mirror::Class*
1852 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001853 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001854 }
1855
Elliott Hughes82914b62012-04-09 15:56:29 -07001856 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001857 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001858}
1859
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001860mirror::Class* ClassLinker::DefineClass(const char* descriptor,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07001861 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001862 const DexFile& dex_file,
1863 const DexFile::ClassDef& dex_class_def) {
Ian Rogers1f539342012-10-03 21:09:42 -07001864 Thread* self = Thread::Current();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001865 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001866 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001867 bool should_allocate = false;
1868
Brian Carlstromaded5f72011-10-07 17:15:04 -07001869 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001870 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001871 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001872 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001873 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001874 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001875 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001876 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001877 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07001878 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
1879 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001880 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001881 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001882 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001883 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001884 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001885 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001886 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001887 should_allocate = true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001888 }
1889 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001890 should_allocate = true;
1891 }
1892
1893 if (should_allocate) {
1894 // Allocate a class with the status of not ready.
1895 // Interface object should get the right size here. Regular class will
1896 // figure out the right size later and be replaced with one of the right
1897 // size when the class becomes resolved.
1898 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001899 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001900 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001901 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07001902 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001903 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001904 klass->SetDexCache(FindDexCache(dex_file));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001905 LoadClass(dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001906 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07001907 if (self->IsExceptionPending()) {
1908 // An exception occured during load, set status to erroneous while holding klass' lock in case
1909 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001910 if (!klass->IsErroneous()) {
1911 klass->SetStatus(mirror::Class::kStatusError, self);
1912 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001913 return nullptr;
1914 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001915 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001916
Mathieu Chartier590fee92013-09-13 13:46:47 -07001917 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001918 mirror::Class* existing = InsertClass(descriptor, klass.Get(), Hash(descriptor));
Ian Rogersc114b5f2014-07-21 08:55:01 -07001919 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001920 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
1921 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001922 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001923 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001924
Brian Carlstromaded5f72011-10-07 17:15:04 -07001925 // Finish loading (if necessary) by finding parents
1926 CHECK(!klass->IsLoaded());
1927 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1928 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001929 if (!klass->IsErroneous()) {
1930 klass->SetStatus(mirror::Class::kStatusError, self);
1931 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001932 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001933 }
1934 CHECK(klass->IsLoaded());
1935 // Link the class (if necessary)
1936 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001937 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001938 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001939
1940 mirror::Class* new_class = nullptr;
1941 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001942 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001943 if (!klass->IsErroneous()) {
1944 klass->SetStatus(mirror::Class::kStatusError, self);
1945 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001946 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001947 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001948 CHECK(new_class != nullptr) << descriptor;
1949 CHECK(new_class->IsResolved()) << descriptor;
1950
1951 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001952
1953 /*
1954 * We send CLASS_PREPARE events to the debugger from here. The
1955 * definition of "preparation" is creating the static fields for a
1956 * class and initializing them to the standard default values, but not
1957 * executing any code (that comes later, during "initialization").
1958 *
1959 * We did the static preparation in LinkClass.
1960 *
1961 * The class has been prepared and resolved but possibly not yet verified
1962 * at this point.
1963 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001964 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001965
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001966 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001967}
1968
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001969uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
1970 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001971 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001972 size_t num_ref = 0;
1973 size_t num_32 = 0;
1974 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001975 if (class_data != NULL) {
1976 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1977 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001978 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001979 char c = descriptor[0];
1980 if (c == 'L' || c == '[') {
1981 num_ref++;
1982 } else if (c == 'J' || c == 'D') {
1983 num_64++;
1984 } else {
1985 num_32++;
1986 }
1987 }
1988 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001989 return mirror::Class::ComputeClassSize(false, 0, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001990}
1991
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001992OatFile::OatClass ClassLinker::GetOatClass(const DexFile& dex_file, uint16_t class_def_idx) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001993 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Ian Rogers19846512012-02-24 11:42:47 -08001994 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001995 CHECK(oat_file != NULL) << dex_file.GetLocation();
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001996 uint dex_location_checksum = dex_file.GetLocationChecksum();
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001997 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation().c_str(),
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001998 &dex_location_checksum);
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001999 CHECK(oat_dex_file != NULL) << dex_file.GetLocation();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002000 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002001}
2002
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002003static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2004 uint32_t method_idx) {
2005 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
2006 const byte* class_data = dex_file.GetClassData(class_def);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002007 CHECK(class_data != NULL);
2008 ClassDataItemIterator it(dex_file, class_data);
2009 // Skip fields
2010 while (it.HasNextStaticField()) {
2011 it.Next();
2012 }
2013 while (it.HasNextInstanceField()) {
2014 it.Next();
2015 }
2016 // Process methods
2017 size_t class_def_method_index = 0;
2018 while (it.HasNextDirectMethod()) {
2019 if (it.GetMemberIndex() == method_idx) {
2020 return class_def_method_index;
2021 }
2022 class_def_method_index++;
2023 it.Next();
2024 }
2025 while (it.HasNextVirtualMethod()) {
2026 if (it.GetMemberIndex() == method_idx) {
2027 return class_def_method_index;
2028 }
2029 class_def_method_index++;
2030 it.Next();
2031 }
2032 DCHECK(!it.HasNext());
2033 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2034 return 0;
2035}
2036
Ian Rogersef7d42f2014-01-06 12:55:46 -08002037const OatFile::OatMethod ClassLinker::GetOatMethodFor(mirror::ArtMethod* method) {
Ian Rogers19846512012-02-24 11:42:47 -08002038 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002039 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002040 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002041 size_t oat_method_index;
2042 if (method->IsStatic() || method->IsDirect()) {
2043 // Simple case where the oat method index was stashed at load time.
2044 oat_method_index = method->GetMethodIndex();
2045 } else {
2046 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2047 // by search for its position in the declared virtual methods.
2048 oat_method_index = declaring_class->NumDirectMethods();
2049 size_t end = declaring_class->NumVirtualMethods();
2050 bool found = false;
2051 for (size_t i = 0; i < end; i++) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08002052 if (declaring_class->GetVirtualMethod(i) == method) {
2053 found = true;
2054 break;
2055 }
Ian Rogersf320b632012-03-13 18:47:47 -07002056 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002057 }
2058 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method);
2059 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002060 DCHECK_EQ(oat_method_index,
2061 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002062 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002063 method->GetDexMethodIndex()));
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002064 const OatFile::OatClass oat_class = GetOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2065 declaring_class->GetDexClassDefIndex());
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002066
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002067 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002068}
2069
2070// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002071const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002072 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002073 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002074 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002075 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002076 const void* result = GetOatMethodFor(method).GetQuickCode();
2077 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002078 if (method->IsNative()) {
2079 // No code and native? Use generic trampoline.
2080 result = GetQuickGenericJniTrampoline();
2081 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002082 // No code? Do we expect portable code?
2083 result = GetQuickToPortableBridge();
2084 } else {
2085 // No code? You must mean to go into the interpreter.
2086 result = GetQuickToInterpreterBridge();
2087 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002088 }
2089 return result;
TDYa12785321912012-04-01 15:24:56 -07002090}
2091
Ian Rogersef7d42f2014-01-06 12:55:46 -08002092const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2093 bool* have_portable_code) {
2094 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2095 *have_portable_code = false;
2096 if (method->IsProxyMethod()) {
2097 return GetPortableProxyInvokeHandler();
2098 }
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002099 const OatFile::OatMethod oat_method = GetOatMethodFor(method);
2100 const void* result = oat_method.GetPortableCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002101 if (result == nullptr) {
Sebastien Hertz7ec2f1c2014-03-27 20:06:47 +01002102 if (oat_method.GetQuickCode() == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002103 // No code? You must mean to go into the interpreter.
2104 result = GetPortableToInterpreterBridge();
2105 } else {
2106 // No code? But there's quick code, so use a bridge.
2107 result = GetPortableToQuickBridge();
2108 }
2109 } else {
2110 *have_portable_code = true;
2111 }
2112 return result;
2113}
2114
2115const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2116 uint32_t method_idx) {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002117 const OatFile::OatClass oat_class = GetOatClass(dex_file, class_def_idx);
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002118 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002119 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002120}
2121
2122const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2123 uint32_t method_idx) {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002124 const OatFile::OatClass oat_class = GetOatClass(dex_file, class_def_idx);
Ian Rogersef7d42f2014-01-06 12:55:46 -08002125 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002126 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002127}
2128
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002129// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002130static bool NeedsInterpreter(
2131 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2132 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002133 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002134 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002135 // May return true for native code, in the case of generic JNI
2136 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002137 return true;
2138 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002139#ifdef ART_SEA_IR_MODE
2140 ScopedObjectAccess soa(Thread::Current());
2141 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2142 LOG(INFO) << "Found " << PrettyMethod(method);
2143 return false;
2144 }
2145#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002146 // If interpreter mode is enabled, every method (except native and proxy) must
2147 // be run with interpreter.
2148 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2149 !method->IsNative() && !method->IsProxyMethod();
2150}
2151
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002152void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002153 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002154 if (klass->NumDirectMethods() == 0) {
2155 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002156 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002157 Runtime* runtime = Runtime::Current();
2158 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Ian Rogers1c829822013-09-30 18:18:50 -07002159 return; // OAT file unavailable.
Ian Rogers19846512012-02-24 11:42:47 -08002160 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07002161 const DexFile& dex_file = klass->GetDexFile();
2162 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002163 CHECK(dex_class_def != nullptr);
2164 const byte* class_data = dex_file.GetClassData(*dex_class_def);
2165 // There should always be class data if there were direct methods.
2166 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002167 const OatFile::OatClass oat_class = GetOatClass(dex_file, klass->GetDexClassDefIndex());
Ian Rogers19846512012-02-24 11:42:47 -08002168 ClassDataItemIterator it(dex_file, class_data);
2169 // Skip fields
2170 while (it.HasNextStaticField()) {
2171 it.Next();
2172 }
2173 while (it.HasNextInstanceField()) {
2174 it.Next();
2175 }
Ian Rogers1c829822013-09-30 18:18:50 -07002176 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002177 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002178 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002179 if (!method->IsStatic()) {
2180 // Only update static methods.
2181 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002182 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002183 const void* portable_code = oat_class.GetOatMethod(method_index).GetPortableCode();
2184 const void* quick_code = oat_class.GetOatMethod(method_index).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002185 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2186 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002187 if (enter_interpreter) {
2188 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002189 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002190 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
2191 quick_code = GetQuickGenericJniTrampoline();
Ian Rogers1a570662014-03-12 01:02:21 -07002192 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002193 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002194 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002195 quick_code = GetQuickToInterpreterBridge();
2196 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002197 } else {
2198 if (portable_code == nullptr) {
2199 portable_code = GetPortableToQuickBridge();
2200 } else {
2201 have_portable_code = true;
2202 }
2203 if (quick_code == nullptr) {
2204 quick_code = GetQuickToPortableBridge();
2205 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002206 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002207 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2208 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002209 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002210 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002211}
2212
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002213void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method, const OatFile::OatClass* oat_class,
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002214 const DexFile& dex_file, uint32_t dex_method_index,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002215 uint32_t method_index) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002216 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002217 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2218 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002219 // Every kind of method should at least get an invoke stub from the oat_method.
2220 // non-abstract methods also get their code pointers.
2221 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002222 oat_method.LinkMethod(method.Get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002223
Jeff Hao16743632013-05-08 10:59:04 -07002224 // Install entry point from interpreter.
Jeff Hao790ad902013-05-22 15:02:08 -07002225 Runtime* runtime = Runtime::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002226 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002227 method->GetEntryPointFromQuickCompiledCode(),
2228 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002229 if (enter_interpreter && !method->IsNative()) {
Ian Rogers848871b2013-08-05 10:56:33 -07002230 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002231 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002232 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002233 }
2234
Brian Carlstrom92827a52011-10-10 15:50:01 -07002235 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002236 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2237 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002238 return;
2239 }
Ian Rogers19846512012-02-24 11:42:47 -08002240
Ian Rogersef7d42f2014-01-06 12:55:46 -08002241 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002242 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002243 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002244 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2245 // after initializing class (see ClassLinker::InitializeClass method).
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002246 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionTrampoline());
2247 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionTrampoline());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002248 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002249 if (!method->IsNative()) {
2250 // Set entry point from compiled code if there's no code or in interpreter only mode.
2251 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2252 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2253 } else {
2254 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniTrampoline());
2255 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2256 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002257 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2258 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2259 have_portable_code = true;
2260 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2261 } else {
2262 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2263 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002264 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002265
Ian Rogers62d6c772013-02-27 08:32:07 -08002266 if (method->IsNative()) {
2267 // Unregistering restores the dlsym lookup stub.
2268 method->UnregisterNative(Thread::Current());
Andreas Gampe90546832014-03-12 18:07:19 -07002269
2270 if (enter_interpreter) {
2271 // We have a native method here without code. Then it should have either the GenericJni
2272 // trampoline as entrypoint (non-static), or the Resolution trampoline (static).
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002273 DCHECK(method->GetEntryPointFromQuickCompiledCode() == GetQuickResolutionTrampoline()
Andreas Gampe9a6a99a2014-03-14 07:52:20 -07002274 || method->GetEntryPointFromQuickCompiledCode() == GetQuickGenericJniTrampoline());
Andreas Gampe90546832014-03-12 18:07:19 -07002275 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002276 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002277
Ian Rogers62d6c772013-02-27 08:32:07 -08002278 // Allow instrumentation its chance to hijack code.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002279 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002280 method->GetEntryPointFromQuickCompiledCode(),
2281 method->GetEntryPointFromPortableCompiledCode(),
2282 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002283}
2284
Brian Carlstromf615a612011-07-23 12:50:34 -07002285void ClassLinker::LoadClass(const DexFile& dex_file,
2286 const DexFile::ClassDef& dex_class_def,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002287 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002288 mirror::ClassLoader* class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002289 CHECK(klass.Get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002290 CHECK(klass->GetDexCache() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002291 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002292 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002293 CHECK(descriptor != NULL);
2294
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002295 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002296 if (kUseBakerOrBrooksReadBarrier) {
2297 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002298 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002299 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07002300 // Make sure that none of our runtime-only flags are set.
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002301 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002302 klass->SetAccessFlags(access_flags);
2303 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002304 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002305 klass->SetStatus(mirror::Class::kStatusIdx, NULL);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002306
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002307 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002308 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002309
Ian Rogers0571d352011-11-03 19:51:38 -07002310 const byte* class_data = dex_file.GetClassData(dex_class_def);
2311 if (class_data == NULL) {
2312 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002313 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002314
2315 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2316 const OatFile::OatClass oat_class = GetOatClass(dex_file, klass->GetDexClassDefIndex());
2317 LoadClassMembers(dex_file, class_data, klass, class_loader, &oat_class);
2318 } else {
2319 LoadClassMembers(dex_file, class_data, klass, class_loader, nullptr);
2320 }
2321}
2322
2323void ClassLinker::LoadClassMembers(const DexFile& dex_file,
2324 const byte* class_data,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002325 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002326 mirror::ClassLoader* class_loader,
2327 const OatFile::OatClass* oat_class) {
2328 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002329 ClassDataItemIterator it(dex_file, class_data);
Ian Rogers50b35e22012-10-04 10:09:15 -07002330 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07002331 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002332 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
2333 if (UNLIKELY(statics == NULL)) {
2334 CHECK(self->IsExceptionPending()); // OOME.
2335 return;
2336 }
2337 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002338 }
2339 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002340 mirror::ObjectArray<mirror::ArtField>* fields =
2341 AllocArtFieldArray(self, it.NumInstanceFields());
2342 if (UNLIKELY(fields == NULL)) {
2343 CHECK(self->IsExceptionPending()); // OOME.
2344 return;
2345 }
2346 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002347 }
2348 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002349 StackHandleScope<1> hs(self);
2350 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
2351 if (UNLIKELY(sfield.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002352 CHECK(self->IsExceptionPending()); // OOME.
2353 return;
2354 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002355 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002356 LoadField(dex_file, it, klass, sfield);
2357 }
2358 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002359 StackHandleScope<1> hs(self);
2360 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
2361 if (UNLIKELY(ifield.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002362 CHECK(self->IsExceptionPending()); // OOME.
2363 return;
2364 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002365 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002366 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002367 }
2368
Ian Rogers0571d352011-11-03 19:51:38 -07002369 // Load methods.
2370 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002371 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002372 mirror::ObjectArray<mirror::ArtMethod>* directs =
2373 AllocArtMethodArray(self, it.NumDirectMethods());
2374 if (UNLIKELY(directs == NULL)) {
2375 CHECK(self->IsExceptionPending()); // OOME.
2376 return;
2377 }
2378 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002379 }
Ian Rogers0571d352011-11-03 19:51:38 -07002380 if (it.NumVirtualMethods() != 0) {
2381 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002382 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2383 AllocArtMethodArray(self, it.NumVirtualMethods());
2384 if (UNLIKELY(virtuals == NULL)) {
2385 CHECK(self->IsExceptionPending()); // OOME.
2386 return;
2387 }
2388 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002389 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002390 size_t class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002391 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002392 StackHandleScope<1> hs(self);
2393 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
2394 if (UNLIKELY(method.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002395 CHECK(self->IsExceptionPending()); // OOME.
2396 return;
2397 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002398 klass->SetDirectMethod(i, method.Get());
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002399 if (oat_class != nullptr) {
2400 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Ian Rogers0571d352011-11-03 19:51:38 -07002401 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002402 method->SetMethodIndex(class_def_method_index);
2403 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002404 }
2405 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002406 StackHandleScope<1> hs(self);
2407 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
2408 if (UNLIKELY(method.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002409 CHECK(self->IsExceptionPending()); // OOME.
2410 return;
2411 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002412 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002413 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002414 if (oat_class != nullptr) {
2415 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Ian Rogers0571d352011-11-03 19:51:38 -07002416 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002417 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002418 }
2419 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002420}
2421
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002422void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002423 Handle<mirror::Class> klass, Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002424 uint32_t field_idx = it.GetMemberIndex();
2425 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002426 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002427 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002428}
2429
Brian Carlstromea46f952013-07-30 01:26:50 -07002430mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002431 const ClassDataItemIterator& it,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002432 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002433 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002434 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002435 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002436
Brian Carlstromea46f952013-07-30 01:26:50 -07002437 mirror::ArtMethod* dst = AllocArtMethod(self);
Ian Rogersa436fde2013-08-27 23:34:06 -07002438 if (UNLIKELY(dst == NULL)) {
2439 CHECK(self->IsExceptionPending()); // OOME.
2440 return NULL;
2441 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002442 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002443
Ian Rogers50b35e22012-10-04 10:09:15 -07002444 const char* old_cause = self->StartAssertNoThreadSuspension("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002445 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002446 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002447 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002448
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002449 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
Ian Rogers19846512012-02-24 11:42:47 -08002450 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002451 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002452
Ian Rogers241b5de2013-10-09 17:58:57 -07002453 uint32_t access_flags = it.GetMemberAccessFlags();
2454
Ian Rogersdfb325e2013-10-30 01:00:44 -07002455 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002456 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002457 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2458 // Void return type.
2459 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
2460 klass->SetFinalizable();
2461 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07002462 std::string klass_descriptor = klass->GetDescriptor();
Ian Rogersdfb325e2013-10-30 01:00:44 -07002463 // The Enum class declares a "final" finalize() method to prevent subclasses from
2464 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2465 // subclasses, so we exclude it here.
2466 // We also want to avoid setting the flag on Object, where we know that finalize() is
2467 // empty.
Mathieu Chartierf8322842014-05-16 10:59:25 -07002468 if (klass_descriptor.compare("Ljava/lang/Object;") != 0 &&
2469 klass_descriptor.compare("Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002470 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002471 }
2472 }
2473 }
2474 } else if (method_name[0] == '<') {
2475 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002476 bool is_init = (strcmp("<init>", method_name) == 0);
2477 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002478 if (UNLIKELY(!is_init && !is_clinit)) {
2479 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2480 } else {
2481 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2482 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002483 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002484 access_flags |= kAccConstructor;
2485 }
2486 }
2487 }
2488 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002489
Ian Rogers50b35e22012-10-04 10:09:15 -07002490 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002491 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002492}
2493
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002494void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002495 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002496 StackHandleScope<1> hs(self);
2497 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
2498 CHECK(dex_cache.Get() != NULL) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002499 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002500}
2501
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002502void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002503 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002504 CHECK(dex_cache.Get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002505 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002506 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002507}
2508
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002509bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002510 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002511 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002512 mirror::DexCache* dex_cache = GetDexCache(i);
2513 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002514 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002515 }
2516 }
2517 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002518}
2519
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002520bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002521 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002522 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002523}
2524
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002525void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002526 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002527 dex_lock_.AssertExclusiveHeld(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002528 CHECK(dex_cache.Get() != NULL) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002529 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2530 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002531 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002532 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002533 if (log_new_dex_caches_roots_) {
2534 // TODO: This is not safe if we can remove dex caches.
2535 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2536 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002537}
2538
Brian Carlstromaded5f72011-10-07 17:15:04 -07002539void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002540 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002541 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002542 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002543 if (IsDexFileRegisteredLocked(dex_file)) {
2544 return;
2545 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002546 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002547 // Don't alloc while holding the lock, since allocation may need to
2548 // suspend all threads and another thread may need the dex_lock_ to
2549 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002550 StackHandleScope<1> hs(self);
2551 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
2552 CHECK(dex_cache.Get() != NULL) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002553 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002554 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002555 if (IsDexFileRegisteredLocked(dex_file)) {
2556 return;
2557 }
2558 RegisterDexFileLocked(dex_file, dex_cache);
2559 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002560}
2561
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002562void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002563 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002564 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002565 RegisterDexFileLocked(dex_file, dex_cache);
2566}
2567
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002568mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002569 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002570 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002571 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002572 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002573 if (dex_cache->GetDexFile() == &dex_file) {
2574 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002575 }
2576 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002577 // Search matching by location name.
2578 std::string location(dex_file.GetLocation());
2579 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002580 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002581 if (dex_cache->GetDexFile()->GetLocation() == location) {
2582 return dex_cache;
2583 }
2584 }
2585 // Failure, dump diagnostic and abort.
2586 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002587 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002588 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
2589 }
2590 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002591 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002592}
2593
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002594void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002595 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08002596 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002597 mirror::DexCache* dex_cache = GetDexCache(i);
2598 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08002599 }
2600}
2601
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002602mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002603 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Ian Rogersa436fde2013-08-27 23:34:06 -07002604 if (UNLIKELY(klass == NULL)) {
2605 return NULL;
2606 }
2607 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002608}
2609
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002610mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
2611 Primitive::Type type) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002612 CHECK(primitive_class != NULL);
Ian Rogers1f539342012-10-03 21:09:42 -07002613 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002614 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002615 StackHandleScope<1> hs(self);
2616 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002617 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002618 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002619 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002620 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
2621 const char* descriptor = Primitive::Descriptor(type);
2622 mirror::Class* existing = InsertClass(descriptor, primitive_class, Hash(descriptor));
Ian Rogersc8982582012-09-07 16:53:25 -07002623 CHECK(existing == NULL) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002624 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07002625}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002626
Brian Carlstrombe977852011-07-19 14:54:54 -07002627// Create an array class (i.e. the class object for the array, not the
2628// array itself). "descriptor" looks like "[C" or "[[[[B" or
2629// "[Ljava/lang/String;".
2630//
2631// If "descriptor" refers to an array of primitives, look up the
2632// primitive type's internally-generated class object.
2633//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002634// "class_loader" is the class loader of the class that's referring to
2635// us. It's used to ensure that we're looking for the element type in
2636// the right context. It does NOT become the class loader for the
2637// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07002638//
2639// Returns NULL with an exception raised on failure.
Ian Rogers98379392014-02-24 16:53:16 -08002640mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002641 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002642 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002643 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002644 StackHandleScope<2> hs(self);
2645 Handle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1, class_loader)));
2646 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002647 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002648 // We need to accept erroneous classes as component types.
2649 component_type.Assign(LookupClass(descriptor + 1, class_loader.Get()));
2650 if (component_type.Get() == nullptr) {
2651 DCHECK(self->IsExceptionPending());
2652 return nullptr;
2653 } else {
2654 self->ClearException();
2655 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002656 }
Ian Rogers2d10b202014-05-12 19:15:18 -07002657 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
2658 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
2659 return nullptr;
2660 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002661 // See if the component type is already loaded. Array classes are
2662 // always associated with the class loader of their underlying
2663 // element type -- an array of Strings goes with the loader for
2664 // java/lang/String -- so we need to look for it there. (The
2665 // caller should have checked for the existence of the class
2666 // before calling here, but they did so with *their* class loader,
2667 // not the component type's loader.)
2668 //
2669 // If we find it, the caller adds "loader" to the class' initiating
2670 // loader list, which should prevent us from going through this again.
2671 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002672 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002673 // are the same, because our caller (FindClass) just did the
2674 // lookup. (Even if we get this wrong we still have correct behavior,
2675 // because we effectively do this lookup again when we add the new
2676 // class to the hash table --- necessary because of possible races with
2677 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002678 if (class_loader.Get() != component_type->GetClassLoader()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002679 mirror::Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002680 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002681 return new_class;
2682 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002683 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002684
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002685 // Fill out the fields in the Class.
2686 //
2687 // It is possible to execute some methods against arrays, because
2688 // all arrays are subclasses of java_lang_Object_, so we need to set
2689 // up a vtable. We can just point at the one in java_lang_Object_.
2690 //
2691 // Array classes are simple enough that we don't need to do a full
2692 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002693 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002694 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002695 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002696 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002697 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002698 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002699 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002700 } else if (strcmp(descriptor, class_roots_descriptors_[kJavaLangStringArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002701 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002702 } else if (strcmp(descriptor,
2703 class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002704 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002705 } else if (strcmp(descriptor,
2706 class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002707 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002708 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002709 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002710 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002711 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002712 }
2713 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002714 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002715 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002716 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002717 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002718 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002719 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002720 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002721 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002722 DCHECK(new_class->GetComponentType() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002723 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002724 new_class->SetSuperClass(java_lang_Object);
2725 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002726 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002727 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002728 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
2729 new_class->PopulateEmbeddedImtAndVTable();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002730 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002731 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002732 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002733
2734
2735 // All arrays have java/lang/Cloneable and java/io/Serializable as
2736 // interfaces. We need to set that up here, so that stuff like
2737 // "instanceof" works right.
2738 //
2739 // Note: The GC could run during the call to FindSystemClass,
2740 // so we need to make sure the class object is GC-valid while we're in
2741 // there. Do this by clearing the interface list so the GC will just
2742 // think that the entries are null.
2743
2744
2745 // Use the single, global copies of "interfaces" and "iftable"
2746 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002747 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002748 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002749 CHECK(array_iftable != nullptr);
2750 new_class->SetIfTable(array_iftable);
2751 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002752
Elliott Hughes00626c22013-06-14 15:04:14 -07002753 // Inherit access flags from the component type.
2754 int access_flags = new_class->GetComponentType()->GetAccessFlags();
2755 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2756 access_flags &= kAccJavaFlagsMask;
2757 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002758 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07002759 access_flags |= kAccAbstract | kAccFinal;
2760 access_flags &= ~kAccInterface;
2761
2762 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002763
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002764 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), Hash(descriptor));
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002765 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002766 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002767 }
2768 // Another thread must have loaded the class after we
2769 // started but before we finished. Abandon what we've
2770 // done.
2771 //
2772 // (Yes, this happens.)
2773
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002774 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002775}
2776
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002777mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07002778 switch (type) {
2779 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002780 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07002781 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002782 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07002783 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002784 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07002785 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002786 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07002787 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002788 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07002789 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002790 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07002791 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002792 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07002793 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002794 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07002795 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002796 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07002797 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002798 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07002799 }
Elliott Hughesbd935992011-08-22 11:59:34 -07002800 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002801 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07002802 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002803}
2804
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002805mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
2806 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002807 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002808 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08002809 std::string source;
2810 if (dex_cache != NULL) {
2811 source += " from ";
2812 source += dex_cache->GetLocation()->ToModifiedUtf8();
2813 }
2814 LOG(INFO) << "Loaded class " << descriptor << source;
2815 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002816 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07002817 mirror::Class* existing =
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002818 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002819 if (existing != NULL) {
2820 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07002821 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002822 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == NULL &&
2823 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002824 // Check a class loaded with the system class loader matches one in the image if the class
2825 // is in the image.
2826 existing = LookupClassFromImage(descriptor);
2827 if (existing != NULL) {
2828 CHECK(klass == existing);
2829 }
2830 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08002831 VerifyObject(klass);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002832 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002833 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002834 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002835 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002836 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002837}
2838
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002839mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
2840 size_t hash) {
2841 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2842 mirror::Class* existing =
2843 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
2844
2845 if (existing == nullptr) {
2846 CHECK(klass->IsProxyClass());
2847 return nullptr;
2848 }
2849
2850 CHECK_NE(existing, klass) << descriptor;
2851 CHECK(!existing->IsResolved()) << descriptor;
2852 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
2853
2854 for (auto it = class_table_.lower_bound(hash), end = class_table_.end(); it != end && it->first == hash;
2855 ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002856 mirror::Class* klass = it->second.Read();
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07002857 if (klass == existing) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002858 class_table_.erase(it);
2859 break;
2860 }
2861 }
2862
2863 CHECK(!klass->IsTemp()) << descriptor;
2864 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
2865 dex_cache_image_class_lookup_required_) {
2866 // Check a class loaded with the system class loader matches one in the image if the class
2867 // is in the image.
2868 existing = LookupClassFromImage(descriptor);
2869 if (existing != nullptr) {
2870 CHECK(klass == existing) << descriptor;
2871 }
2872 }
2873 VerifyObject(klass);
2874
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002875 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002876 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002877 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002878 }
2879
2880 return existing;
2881}
2882
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002883bool ClassLinker::RemoveClass(const char* descriptor, const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002884 size_t hash = Hash(descriptor);
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002885 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Brian Carlstromf3632832014-05-20 15:36:53 -07002886 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
2887 it != end && it->first == hash;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002888 ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002889 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002890 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002891 class_table_.erase(it);
Brian Carlstromae826982011-11-09 01:33:42 -08002892 return true;
2893 }
2894 }
2895 return false;
2896}
2897
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002898mirror::Class* ClassLinker::LookupClass(const char* descriptor,
2899 const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002900 size_t hash = Hash(descriptor);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002901 {
2902 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2903 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
2904 if (result != NULL) {
2905 return result;
2906 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07002907 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002908 if (class_loader != NULL || !dex_cache_image_class_lookup_required_) {
2909 return NULL;
2910 } else {
2911 // Lookup failed but need to search dex_caches_.
2912 mirror::Class* result = LookupClassFromImage(descriptor);
2913 if (result != NULL) {
2914 InsertClass(descriptor, result, hash);
2915 } else {
2916 // Searching the image dex files/caches failed, we don't want to get into this situation
2917 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
2918 // classes into the class table.
2919 const int32_t kMaxFailedDexCacheLookups = 1000;
2920 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
2921 MoveImageClassesToClassTable();
2922 }
2923 }
2924 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002925 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002926}
2927
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002928mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
2929 const mirror::ClassLoader* class_loader,
2930 size_t hash) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002931 auto end = class_table_.end();
2932 for (auto it = class_table_.lower_bound(hash); it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002933 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002934 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002935 if (kIsDebugBuild) {
2936 // Check for duplicates in the table.
2937 for (++it; it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002938 mirror::Class* klass2 = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002939 CHECK(!(klass2->GetClassLoader() == class_loader &&
2940 klass2->DescriptorEquals(descriptor)))
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002941 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
2942 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002943 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002944 }
Ian Rogers5d76c432011-10-31 21:42:49 -07002945 return klass;
2946 }
2947 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002948 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002949}
2950
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002951static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
2952 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2953 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
2954 CHECK(image != NULL);
2955 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
2956 return root->AsObjectArray<mirror::DexCache>();
2957}
2958
2959void ClassLinker::MoveImageClassesToClassTable() {
2960 Thread* self = Thread::Current();
2961 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2962 if (!dex_cache_image_class_lookup_required_) {
2963 return; // All dex cache classes are already in the class table.
2964 }
2965 const char* old_no_suspend_cause =
2966 self->StartAssertNoThreadSuspension("Moving image classes to class table");
2967 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002968 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2969 mirror::DexCache* dex_cache = dex_caches->Get(i);
2970 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
2971 for (int32_t j = 0; j < types->GetLength(); j++) {
2972 mirror::Class* klass = types->Get(j);
2973 if (klass != NULL) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002974 DCHECK(klass->GetClassLoader() == NULL);
Mathieu Chartierf8322842014-05-16 10:59:25 -07002975 std::string descriptor = klass->GetDescriptor();
2976 size_t hash = Hash(descriptor.c_str());
2977 mirror::Class* existing = LookupClassFromTableLocked(descriptor.c_str(), NULL, hash);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002978 if (existing != NULL) {
2979 CHECK(existing == klass) << PrettyClassAndClassLoader(existing) << " != "
2980 << PrettyClassAndClassLoader(klass);
2981 } else {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002982 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002983 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002984 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002985 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002986 }
2987 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002988 }
2989 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002990 dex_cache_image_class_lookup_required_ = false;
2991 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
2992}
2993
2994mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
2995 Thread* self = Thread::Current();
2996 const char* old_no_suspend_cause =
2997 self->StartAssertNoThreadSuspension("Image class lookup");
2998 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
2999 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3000 mirror::DexCache* dex_cache = dex_caches->Get(i);
3001 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003002 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003003 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
3004 if (string_id != NULL) {
3005 const DexFile::TypeId* type_id =
3006 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
3007 if (type_id != NULL) {
3008 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3009 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
3010 if (klass != NULL) {
3011 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3012 return klass;
3013 }
3014 }
3015 }
3016 }
3017 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3018 return NULL;
3019}
3020
3021void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3022 result.clear();
3023 if (dex_cache_image_class_lookup_required_) {
3024 MoveImageClassesToClassTable();
3025 }
3026 size_t hash = Hash(descriptor);
3027 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003028 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
Mathieu Chartier02e25112013-08-14 16:14:24 -07003029 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003030 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003031 if (klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003032 result.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003033 }
3034 }
3035}
3036
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003037void ClassLinker::VerifyClass(Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003038 // TODO: assert that the monitor on the Class is held
Ian Rogers1f539342012-10-03 21:09:42 -07003039 Thread* self = Thread::Current();
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003040 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003041
Ian Rogers9ffb0392012-09-10 11:56:50 -07003042 // Don't attempt to re-verify if already sufficiently verified.
3043 if (klass->IsVerified() ||
3044 (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler())) {
jeffhao98eacac2011-09-14 16:11:53 -07003045 return;
3046 }
3047
Ian Rogers9ffb0392012-09-10 11:56:50 -07003048 // The class might already be erroneous, for example at compile time if we attempted to verify
3049 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003050 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003051 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003052 return;
3053 }
3054
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003055 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003056 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003057 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003058 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003059 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003060 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003061 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003062 }
jeffhao98eacac2011-09-14 16:11:53 -07003063
Jeff Hao4a200f52014-04-01 14:58:49 -07003064 // Skip verification if disabled.
3065 if (!Runtime::Current()->IsVerificationEnabled()) {
3066 klass->SetStatus(mirror::Class::kStatusVerified, self);
3067 return;
3068 }
3069
Ian Rogers9ffb0392012-09-10 11:56:50 -07003070 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003071 StackHandleScope<2> hs(self);
3072 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
3073 if (super.Get() != NULL) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003074 // Acquire lock to prevent races on verifying the super class.
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003075 ObjectLock<mirror::Class> lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003076
3077 if (!super->IsVerified() && !super->IsErroneous()) {
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003078 VerifyClass(super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003079 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003080 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003081 std::string error_msg(
3082 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3083 PrettyDescriptor(klass.Get()).c_str(),
3084 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003085 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003086 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3087 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003088 self->ClearException();
3089 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003090 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3091 if (cause.Get() != nullptr) {
3092 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003093 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003094 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003095 if (Runtime::Current()->IsCompiler()) {
3096 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3097 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003098 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003099 return;
3100 }
3101 }
3102
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003103 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003104 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003105 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003106 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003107 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003108 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003109 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003110 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003111 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3112 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003113 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003114 return;
3115 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003116 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003117 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003118 if (!preverified) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003119 verifier_failure = verifier::MethodVerifier::VerifyClass(klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003120 Runtime::Current()->IsCompiler(),
3121 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003122 }
3123 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003124 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003125 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003126 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3127 << " because: " << error_msg;
3128 }
Ian Rogers1f539342012-10-03 21:09:42 -07003129 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003130 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003131 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003132 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003133 // Even though there were no verifier failures we need to respect whether the super-class
3134 // was verified or requiring runtime reverification.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003135 if (super.Get() == NULL || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003136 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003137 } else {
3138 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003139 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003140 // Pretend a soft failure occured so that we don't consider the class verified below.
3141 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003142 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003143 } else {
3144 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3145 // Soft failures at compile time should be retried at runtime. Soft
3146 // failures at runtime will be handled by slow paths in the generated
3147 // code. Set status accordingly.
3148 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003149 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003150 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003151 klass->SetStatus(mirror::Class::kStatusVerified, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003152 }
3153 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003154 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003155 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003156 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3157 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003158 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003159 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003160 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003161 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003162 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003163 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003164 // Let the interpreter know it by setting the kAccPreverified flag onto each
3165 // method.
3166 // Note: we're going here during compilation and at runtime. When we set the
3167 // kAccPreverified flag when compiling image classes, the flag is recorded
3168 // in the image and is set when loading the image.
3169 klass->SetPreverifiedFlagOnAllMethods();
3170 }
jeffhao98eacac2011-09-14 16:11:53 -07003171}
3172
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003173bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3174 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003175 // If we're compiling, we can only verify the class using the oat file if
3176 // we are not compiling the image or if the class we're verifying is not part of
3177 // the app. In other words, we will only check for preverification of bootclasspath
3178 // classes.
3179 if (Runtime::Current()->IsCompiler()) {
3180 // Are we compiling the bootclasspath?
3181 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3182 return false;
3183 }
3184 // We are compiling an app (not the image).
3185
3186 // Is this an app class? (I.e. not a bootclasspath class)
3187 if (klass->GetClassLoader() != NULL) {
3188 return false;
3189 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003190 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003191
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003192 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003193 // Make this work with gtests, which do not set up the image properly.
3194 // TODO: we should clean up gtests to set up the image path properly.
3195 if (Runtime::Current()->IsCompiler() && (oat_file == NULL)) {
3196 return false;
3197 }
3198
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003199 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07003200 uint dex_location_checksum = dex_file.GetLocationChecksum();
Ian Rogers8d31bbd2013-10-13 10:44:14 -07003201 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation().c_str(),
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07003202 &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003203 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003204 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003205 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003206 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3207 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003208 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003209 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003210 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003211 // Compile time verification failed with a soft error. Compile time verification can fail
3212 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003213 // class ... {
3214 // Foo x;
3215 // .... () {
3216 // if (...) {
3217 // v1 gets assigned a type of resolved class Foo
3218 // } else {
3219 // v1 gets assigned a type of unresolved class Bar
3220 // }
3221 // iput x = v1
3222 // } }
3223 // when we merge v1 following the if-the-else it results in Conflict
3224 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3225 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3226 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3227 // at compile time).
3228 return false;
3229 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003230 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003231 // Compile time verification failed with a hard error. This is caused by invalid instructions
3232 // in the class. These errors are unrecoverable.
3233 return false;
3234 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003235 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003236 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3237 // not loading the class.
3238 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3239 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003240 return false;
3241 }
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003242 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003243 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Mathieu Chartierf8322842014-05-16 10:59:25 -07003244 << klass->GetDescriptor();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003245
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003246 return false;
3247}
3248
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003249void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003250 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003251 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3252 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3253 }
3254 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3255 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3256 }
3257}
3258
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003259void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003260 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003261 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3262 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
3263 if (code_item == NULL) {
3264 return; // native or abstract method
3265 }
3266 if (code_item->tries_size_ == 0) {
3267 return; // nothing to process
3268 }
3269 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
3270 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3271 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3272 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3273 CatchHandlerIterator iterator(handlers_ptr);
3274 for (; iterator.HasNext(); iterator.Next()) {
3275 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3276 // unresolved exception types will be ignored by exception delivery
3277 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003278 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003279 if (exception_type == NULL) {
3280 DCHECK(Thread::Current()->IsExceptionPending());
3281 Thread::Current()->ClearException();
3282 }
3283 }
3284 }
3285 handlers_ptr = iterator.EndDataPointer();
3286 }
3287}
3288
Brian Carlstromea46f952013-07-30 01:26:50 -07003289static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003290static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003291 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003292
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003293mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003294 jobjectArray interfaces, jobject loader,
3295 jobjectArray methods, jobjectArray throws) {
3296 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003297 StackHandleScope<8> hs(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003298 Handle<mirror::Class> klass(hs.NewHandle(
3299 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003300 if (klass.Get() == NULL) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003301 CHECK(self->IsExceptionPending()); // OOME.
3302 return NULL;
3303 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003304 DCHECK(klass->GetClass() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003305 klass->SetObjectSize(sizeof(mirror::Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003306 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003307 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003308 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003309 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003310 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003311 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003312 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003313
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003314 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003315 {
3316 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
3317 if (UNLIKELY(sfields == NULL)) {
3318 CHECK(self->IsExceptionPending()); // OOME.
3319 return NULL;
3320 }
3321 klass->SetSFields(sfields);
3322 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003323 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3324 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003325 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3326 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003327 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003328 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003329 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003330 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003331 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003332 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003333 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3334 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003335 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3336 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003337 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003338 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003339 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003340 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003341 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003342 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003343 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003344
Ian Rogers466bb252011-10-14 03:29:56 -07003345 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003346 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003347 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003348 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003349 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003350 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003351 }
3352 klass->SetDirectMethods(directs);
3353 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003354 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003355 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003356 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003357 }
3358 klass->SetDirectMethod(0, constructor);
3359 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003360
Mathieu Chartier590fee92013-09-13 13:46:47 -07003361 // Create virtual method using specified prototypes.
3362 size_t num_virtual_methods =
3363 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003364 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003365 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3366 num_virtual_methods);
Ian Rogersa436fde2013-08-27 23:34:06 -07003367 if (UNLIKELY(virtuals == NULL)) {
3368 CHECK(self->IsExceptionPending()); // OOME.
3369 return NULL;
3370 }
3371 klass->SetVirtualMethods(virtuals);
3372 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003373 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003374 StackHandleScope<1> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003375 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3376 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003377 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003378 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003379 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003380 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003381 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003382 }
3383 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003384 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003385
3386 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003387 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003388 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003389
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003390 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3391 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003392 {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003393 ObjectLock<mirror::Class> resolution_lock(self, klass); // Must hold lock on object when resolved.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003394 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003395 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003396 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003397 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003398 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003399 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003400 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003401 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003402
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003403 CHECK(klass->IsRetired());
3404 CHECK_NE(klass.Get(), new_class);
3405 klass.Assign(new_class);
3406
3407 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
3408 interfaces_sfield->SetObject<false>(klass.Get(), soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
3409 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
3410 throws_sfield->SetObject<false>(klass.Get(), soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
3411
3412 {
3413 // Lock on klass is released. Lock new class object.
3414 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003415 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003416 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003417
3418 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003419 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003420 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003421 CheckProxyConstructor(klass->GetDirectMethod(0));
3422 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003423 StackHandleScope<2> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003424 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3425 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003426 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003427 Handle<mirror::ArtMethod> virtual_method(hs.NewHandle(klass->GetVirtualMethod(i)));
3428 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003429 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003430
Mathieu Chartier590fee92013-09-13 13:46:47 -07003431 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003432 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003433 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003434 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3435
3436 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003437 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003438 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003439
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003440 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003441 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003442 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003443 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003444 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003445 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003446 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003447 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003448}
3449
Ian Rogersef7d42f2014-01-06 12:55:46 -08003450std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003451 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003452 mirror::String* name = proxy_class->GetName();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003453 DCHECK(name != NULL);
3454 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3455}
3456
Ian Rogersef7d42f2014-01-06 12:55:46 -08003457mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3458 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003459 DCHECK(proxy_class->IsProxyClass());
3460 DCHECK(proxy_method->IsProxyMethod());
3461 // Locate the dex cache of the original interface/Object
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003462 mirror::DexCache* dex_cache = NULL;
Ian Rogers16f93672012-02-14 12:29:06 -08003463 {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003464 mirror::ObjectArray<mirror::Class>* resolved_types = proxy_method->GetDexCacheResolvedTypes();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003465 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003466 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003467 mirror::DexCache* a_dex_cache = GetDexCache(i);
3468 if (a_dex_cache->GetResolvedTypes() == resolved_types) {
3469 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003470 break;
3471 }
3472 }
3473 }
3474 CHECK(dex_cache != NULL);
3475 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003476 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Ian Rogers16f93672012-02-14 12:29:06 -08003477 CHECK(resolved_method != NULL);
3478 return resolved_method;
3479}
3480
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003481
Brian Carlstromea46f952013-07-30 01:26:50 -07003482mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003483 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003484 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003485 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003486 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003487 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003488 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3489 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Nicolas Geoffray167cc7c2014-07-29 08:33:44 +00003490 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3491 // code_ too)
3492 mirror::ArtMethod* constructor =
3493 down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3494 if (constructor == NULL) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003495 CHECK(self->IsExceptionPending()); // OOME.
Nicolas Geoffray167cc7c2014-07-29 08:33:44 +00003496 return NULL;
Ian Rogersa436fde2013-08-27 23:34:06 -07003497 }
Ian Rogers466bb252011-10-14 03:29:56 -07003498 // Make this constructor public and fix the class to be our Proxy version
3499 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003500 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003501 return constructor;
3502}
3503
Brian Carlstromea46f952013-07-30 01:26:50 -07003504static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003505 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003506 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003507 CHECK_STREQ(constructor->GetName(), "<init>");
3508 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3509 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003510 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003511}
3512
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003513mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003514 Handle<mirror::Class> klass,
3515 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003516 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3517 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08003518 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003519 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003520 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003521 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003522 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Ian Rogersa436fde2013-08-27 23:34:06 -07003523 if (UNLIKELY(method == NULL)) {
3524 CHECK(self->IsExceptionPending()); // OOME.
3525 return NULL;
3526 }
Ian Rogers466bb252011-10-14 03:29:56 -07003527
3528 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3529 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003530 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07003531 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003532
Ian Rogers466bb252011-10-14 03:29:56 -07003533 // At runtime the method looks like a reference and argument saving method, clone the code
3534 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003535 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
3536 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07003537 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08003538
Ian Rogersc2b44472011-12-14 21:17:17 -08003539 return method;
3540}
Jesse Wilson95caa792011-10-12 18:14:17 -04003541
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003542static void CheckProxyMethod(Handle<mirror::ArtMethod> method, Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003543 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003544 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003545 CHECK(!prototype->IsFinal());
3546 CHECK(method->IsFinal());
3547 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08003548
3549 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
3550 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
3551 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
3552 CHECK_EQ(prototype->GetDexCacheResolvedMethods(), method->GetDexCacheResolvedMethods());
3553 CHECK_EQ(prototype->GetDexCacheResolvedTypes(), method->GetDexCacheResolvedTypes());
Ian Rogers19846512012-02-24 11:42:47 -08003554 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
3555
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003556 MethodHelper mh(method);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003557 MethodHelper mh2(prototype);
3558 CHECK_STREQ(method->GetName(), prototype->GetName());
3559 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07003560 // More complex sanity - via dex cache
Ian Rogers19846512012-02-24 11:42:47 -08003561 CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04003562}
3563
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003564static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
3565 bool can_init_parents)
3566 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003567 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003568 return true;
3569 }
3570 if (!can_init_statics) {
3571 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07003572 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003573 if (clinit != NULL) {
3574 return false;
3575 }
3576 // Check if there are encoded static values needing initialization.
3577 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003578 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003579 DCHECK(dex_class_def != NULL);
3580 if (dex_class_def->static_values_off_ != 0) {
3581 return false;
3582 }
3583 }
3584 }
3585 if (!klass->IsInterface() && klass->HasSuperClass()) {
3586 mirror::Class* super_class = klass->GetSuperClass();
3587 if (!can_init_parents && !super_class->IsInitialized()) {
3588 return false;
3589 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003590 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003591 return false;
3592 }
3593 }
3594 }
3595 return true;
3596}
3597
Mathieu Chartier590fee92013-09-13 13:46:47 -07003598bool ClassLinker::IsInitialized() const {
3599 return init_done_;
3600}
3601
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003602bool ClassLinker::InitializeClass(Handle<mirror::Class> klass, bool can_init_statics,
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003603 bool can_init_parents) {
3604 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
3605
3606 // Are we already initialized and therefore done?
3607 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
3608 // an initialized class will never change its state.
3609 if (klass->IsInitialized()) {
3610 return true;
3611 }
3612
3613 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003614 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003615 return false;
3616 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003617
Carl Shapirob5573532011-07-12 18:22:59 -07003618 Thread* self = Thread::Current();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003619 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003620 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003621 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003622
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003623 // Re-check under the lock in case another thread initialized ahead of us.
3624 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003625 return true;
3626 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003627
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003628 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003629 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003630 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromd1422f82011-09-28 11:37:09 -07003631 return false;
3632 }
3633
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003634 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003635
3636 if (!klass->IsVerified()) {
jeffhao98eacac2011-09-14 16:11:53 -07003637 VerifyClass(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003638 if (!klass->IsVerified()) {
3639 // We failed to verify, expect either the klass to be erroneous or verification failed at
3640 // compile time.
3641 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07003642 CHECK(self->IsExceptionPending());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003643 } else {
3644 CHECK(Runtime::Current()->IsCompiler());
3645 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07003646 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003647 return false;
3648 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003649 }
3650
Brian Carlstromd1422f82011-09-28 11:37:09 -07003651 // If the class is kStatusInitializing, either this thread is
3652 // initializing higher up the stack or another thread has beat us
3653 // to initializing and we need to wait. Either way, this
3654 // invocation of InitializeClass will not be responsible for
3655 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003656 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07003657 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07003658 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003659 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003660 return true;
3661 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003662 // No. That's fine. Wait for another thread to finish initializing.
3663 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003664 }
3665
3666 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003667 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003668 return false;
3669 }
3670
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003671 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003672
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003673 // From here out other threads may observe that we're initializing and so changes of state
3674 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07003675 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003676 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003677
3678 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003679 }
3680
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003681 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003682 if (!klass->IsInterface() && klass->HasSuperClass()) {
3683 mirror::Class* super_class = klass->GetSuperClass();
3684 if (!super_class->IsInitialized()) {
3685 CHECK(!super_class->IsInterface());
3686 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003687 StackHandleScope<1> hs(self);
3688 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
3689 bool super_initialized = InitializeClass(handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003690 if (!super_initialized) {
3691 // The super class was verified ahead of entering initializing, we should only be here if
3692 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003693 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07003694 << "Super class initialization failed for "
3695 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003696 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003697 << "\nPending exception:\n"
3698 << (self->GetException(NULL) != NULL ? self->GetException(NULL)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003699 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003700 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003701 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003702 return false;
3703 }
Ian Rogers1bddec32012-02-04 12:27:34 -08003704 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003705 }
3706
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003707 if (klass->NumStaticFields() > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003708 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003709 CHECK(dex_class_def != NULL);
Mathieu Chartierf8322842014-05-16 10:59:25 -07003710 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003711 StackHandleScope<2> hs(self);
3712 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07003713 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07003714 EncodedStaticFieldValueIterator it(dex_file, &dex_cache, &class_loader,
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003715 this, *dex_class_def);
3716 if (it.HasNext()) {
3717 CHECK(can_init_statics);
Brian Carlstromf3632832014-05-20 15:36:53 -07003718 // We reordered the fields, so we need to be able to map the
3719 // field indexes to the right fields.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003720 SafeMap<uint32_t, mirror::ArtField*> field_map;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003721 ConstructFieldMap(dex_file, *dex_class_def, klass.Get(), field_map);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003722 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003723 if (Runtime::Current()->IsActiveTransaction()) {
3724 it.ReadValueToField<true>(field_map.Get(i));
3725 } else {
3726 it.ReadValueToField<false>(field_map.Get(i));
3727 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003728 }
3729 }
3730 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003731
Ian Rogersd91d6d62013-09-25 20:26:14 -07003732 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003733 if (clinit != NULL) {
3734 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07003735 JValue result;
3736 clinit->Invoke(self, NULL, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003737 }
3738
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003739 uint64_t t1 = NanoTime();
3740
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003741 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003742 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003743 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003744
3745 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07003746 WrapExceptionInInitializer();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003747 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003748 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003749 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003750 RuntimeStats* global_stats = Runtime::Current()->GetStats();
3751 RuntimeStats* thread_stats = self->GetStats();
3752 ++global_stats->class_init_count;
3753 ++thread_stats->class_init_count;
3754 global_stats->class_init_time_ns += (t1 - t0);
3755 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003756 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003757 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003758 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003759 LOG(INFO) << "Initialized class " << klass->GetDescriptor() << " from " <<
3760 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08003761 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08003762 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003763 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003764 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003765 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003766 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003767}
3768
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003769bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003770 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003771 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003772 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003773 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003774 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08003775 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003776
3777 // When we wake up, repeat the test for init-in-progress. If
3778 // there's an exception pending (only possible if
3779 // "interruptShouldThrow" was set), bail out.
3780 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07003781 WrapExceptionInInitializer();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003782 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003783 return false;
3784 }
3785 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003786 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003787 continue;
3788 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003789 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07003790 // Compile time initialization failed.
3791 return false;
3792 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003793 if (klass->IsErroneous()) {
3794 // The caller wants an exception, but it was thrown in a
3795 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07003796 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003797 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07003798 return false;
3799 }
3800 if (klass->IsInitialized()) {
3801 return true;
3802 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003803 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003804 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003805 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003806 LOG(FATAL) << "Not Reached" << PrettyClass(klass.Get());
Brian Carlstromd1422f82011-09-28 11:37:09 -07003807}
3808
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003809bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003810 if (klass->IsInterface()) {
3811 return true;
3812 }
Ian Rogers151f2212014-05-06 11:27:27 -07003813 // Begin with the methods local to the superclass.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003814 StackHandleScope<2> hs(Thread::Current());
3815 MethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
3816 MethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003817 if (klass->HasSuperClass() &&
3818 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07003819 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
3820 mh.ChangeMethod(klass->GetVTableEntry(i));
3821 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003822 if (mh.GetMethod() != super_mh.GetMethod() &&
3823 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
3824 ThrowLinkageError(klass.Get(),
3825 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003826 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07003827 PrettyMethod(mh.GetMethod()).c_str(),
3828 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003829 return false;
3830 }
3831 }
3832 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003833 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07003834 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
3835 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
3836 for (uint32_t j = 0; j < num_methods; ++j) {
3837 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
3838 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003839 if (mh.GetMethod() != super_mh.GetMethod() &&
3840 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
3841 ThrowLinkageError(klass.Get(),
3842 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003843 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07003844 PrettyMethod(mh.GetMethod()).c_str(),
3845 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003846 return false;
3847 }
3848 }
3849 }
3850 }
3851 return true;
3852}
3853
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003854bool ClassLinker::EnsureInitialized(Handle<mirror::Class> c, bool can_init_fields,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003855 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003856 DCHECK(c.Get() != nullptr);
3857 const bool success = c->IsInitialized() || InitializeClass(c, can_init_fields, can_init_parents);
3858 if (!success && can_init_fields && can_init_parents) {
3859 CHECK(Thread::Current()->IsExceptionPending()) << PrettyClass(c.Get());
Ian Rogers595799e2012-01-11 17:32:51 -08003860 }
3861 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07003862}
3863
Elliott Hughes5fe594f2011-09-08 12:33:17 -07003864void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003865 mirror::Class* c,
3866 SafeMap<uint32_t, mirror::ArtField*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07003867 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07003868 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003869 StackHandleScope<2> hs(Thread::Current());
3870 Handle<mirror::DexCache> dex_cache(hs.NewHandle(c->GetDexCache()));
3871 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(c->GetClassLoader()));
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003872 CHECK(!kMovingFields);
Ian Rogers0571d352011-11-03 19:51:38 -07003873 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003874 field_map.Put(i, ResolveField(dex_file, it.GetMemberIndex(), dex_cache, class_loader, true));
Elliott Hughes5fe594f2011-09-08 12:33:17 -07003875 }
3876}
3877
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003878void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
3879 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
3880 if (fields != nullptr) {
3881 for (int index = 0; index < fields->GetLength(); index ++) {
3882 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
3883 fields->Get(index)->SetDeclaringClass(new_class);
3884 }
3885 }
3886 }
3887
3888 fields = new_class->GetSFields();
3889 if (fields != nullptr) {
3890 for (int index = 0; index < fields->GetLength(); index ++) {
3891 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
3892 fields->Get(index)->SetDeclaringClass(new_class);
3893 }
3894 }
3895 }
3896
3897 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
3898 if (methods != nullptr) {
3899 for (int index = 0; index < methods->GetLength(); index ++) {
3900 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3901 methods->Get(index)->SetDeclaringClass(new_class);
3902 }
3903 }
3904 }
3905
3906 methods = new_class->GetVirtualMethods();
3907 if (methods != nullptr) {
3908 for (int index = 0; index < methods->GetLength(); index ++) {
3909 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3910 methods->Get(index)->SetDeclaringClass(new_class);
3911 }
3912 }
3913 }
3914}
3915
3916bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
3917 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
3918 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003919 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003920
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003921 if (!LinkSuperClass(klass)) {
3922 return false;
3923 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003924 if (!LinkMethods(self, klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003925 return false;
3926 }
3927 if (!LinkInstanceFields(klass)) {
3928 return false;
3929 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003930 size_t class_size;
3931 if (!LinkStaticFields(klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003932 return false;
3933 }
3934 CreateReferenceInstanceOffsets(klass);
3935 CreateReferenceStaticOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003936 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003937
3938 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
3939 // We don't need to retire this class as it has no embedded tables or it was created the
3940 // correct size during class linker initialization.
3941 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
3942
3943 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
3944 klass->PopulateEmbeddedImtAndVTable();
3945 }
3946
3947 // This will notify waiters on klass that saw the not yet resolved
3948 // class in the class_table_ during EnsureResolved.
3949 klass->SetStatus(mirror::Class::kStatusResolved, self);
3950 *new_class = klass.Get();
3951 } else {
3952 CHECK(!klass->IsResolved());
3953 // Retire the temporary class and create the correctly sized resolved class.
3954 *new_class = klass->CopyOf(self, class_size);
3955 if (UNLIKELY(*new_class == NULL)) {
3956 CHECK(self->IsExceptionPending()); // Expect an OOME.
3957 klass->SetStatus(mirror::Class::kStatusError, self);
3958 return false;
3959 }
3960
3961 CHECK_EQ((*new_class)->GetClassSize(), class_size);
3962 StackHandleScope<1> hs(self);
3963 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
3964 ObjectLock<mirror::Class> lock(self, new_class_h);
3965
3966 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
3967
3968 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(), Hash(descriptor));
3969 CHECK(existing == NULL || existing == klass.Get());
3970
3971 // This will notify waiters on temp class that saw the not yet resolved class in the
3972 // class_table_ during EnsureResolved.
3973 klass->SetStatus(mirror::Class::kStatusRetired, self);
3974
3975 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
3976 // This will notify waiters on new_class that saw the not yet resolved
3977 // class in the class_table_ during EnsureResolved.
3978 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003979 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003980 return true;
3981}
3982
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003983bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003984 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003985 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
3986 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003987 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003988 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003989 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07003990 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003991 return false;
3992 }
Ian Rogersbe125a92012-01-11 15:19:49 -08003993 // Verify
3994 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003995 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08003996 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003997 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08003998 return false;
3999 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004000 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004001 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004002 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004003 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004004 if (interfaces != NULL) {
4005 for (size_t i = 0; i < interfaces->Size(); i++) {
4006 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004007 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004008 if (interface == NULL) {
4009 DCHECK(Thread::Current()->IsExceptionPending());
4010 return false;
4011 }
4012 // Verify
4013 if (!klass->CanAccess(interface)) {
4014 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004015 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004016 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004017 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004018 return false;
4019 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004020 }
4021 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004022 // Mark the class as loaded.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004023 klass->SetStatus(mirror::Class::kStatusLoaded, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004024 return true;
4025}
4026
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004027bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004028 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004029 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004030 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004031 if (super != NULL) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004032 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004033 return false;
4034 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004035 return true;
4036 }
4037 if (super == NULL) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004038 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4039 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004040 return false;
4041 }
4042 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004043 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004044 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004045 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004046 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004047 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004048 return false;
4049 }
4050 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004051 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004052 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004053 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004054 return false;
4055 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004056
Brian Carlstromf3632832014-05-20 15:36:53 -07004057 // Inherit kAccClassIsFinalizable from the superclass in case this
4058 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004059 if (super->IsFinalizable()) {
4060 klass->SetFinalizable();
4061 }
4062
Elliott Hughes2da50362011-10-10 16:57:08 -07004063 // Inherit reference flags (if any) from the superclass.
4064 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4065 if (reference_flags != 0) {
4066 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4067 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004068 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004069 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004070 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004071 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004072 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004073 return false;
4074 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004075
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004076 if (kIsDebugBuild) {
4077 // Ensure super classes are fully resolved prior to resolving fields..
4078 while (super != NULL) {
4079 CHECK(super->IsResolved());
4080 super = super->GetSuperClass();
4081 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004082 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004083 return true;
4084}
4085
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004086// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004087bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004088 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004089 if (klass->IsInterface()) {
4090 // No vtable.
4091 size_t count = klass->NumVirtualMethods();
4092 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004093 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004094 return false;
4095 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004096 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004097 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004098 }
jeffhaobdb76512011-09-07 11:43:16 -07004099 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004100 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004101 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07004102 // Link virtual and interface method tables
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004103 return LinkVirtualMethods(self, klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004104 }
4105 return true;
4106}
4107
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004108bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004109 if (klass->HasSuperClass()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004110 uint32_t max_count = klass->NumVirtualMethods() +
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004111 klass->GetSuperClass()->GetVTableLength();
4112 size_t actual_count = klass->GetSuperClass()->GetVTableLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004113 CHECK_LE(actual_count, max_count);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004114 StackHandleScope<3> hs(self);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004115 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
4116 mirror::Class* super_class = klass->GetSuperClass();
4117 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4118 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4119 if (UNLIKELY(vtable.Get() == nullptr)) {
4120 CHECK(self->IsExceptionPending()); // OOME.
4121 return false;
4122 }
4123 int len = super_class->GetVTableLength();
Mingyao Yang1a128582014-07-22 17:33:25 -07004124 for (int i = 0; i < len; i++) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004125 vtable->Set<false>(i, super_class->GetVTableEntry(i));
4126 }
4127 } else {
4128 CHECK(super_class->GetVTable() != nullptr) << PrettyClass(super_class);
4129 vtable = hs.NewHandle(super_class->GetVTable()->CopyOf(self, max_count));
4130 if (UNLIKELY(vtable.Get() == nullptr)) {
4131 CHECK(self->IsExceptionPending()); // OOME.
4132 return false;
4133 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004134 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004135
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004136 // See if any of our virtual methods override the superclass.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004137 MethodHelper local_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4138 MethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004139 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004140 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004141 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004142 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004143 for (; j < actual_count; ++j) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004144 mirror::ArtMethod* super_method = vtable->Get(j);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004145 super_mh.ChangeMethod(super_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004146 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004147 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4148 super_method->GetAccessFlags())) {
Elliott Hughes39717372012-07-13 16:21:23 -07004149 if (super_method->IsFinal()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004150 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
Elliott Hughes39717372012-07-13 16:21:23 -07004151 PrettyMethod(local_method).c_str(),
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004152 super_method->GetDeclaringClassDescriptor());
Elliott Hughes39717372012-07-13 16:21:23 -07004153 return false;
4154 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004155 vtable->Set<false>(j, local_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004156 local_method->SetMethodIndex(j);
4157 break;
4158 } else {
4159 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method)
4160 << " would have incorrectly overridden the package-private method in "
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004161 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004162 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004163 }
4164 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004165 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004166 // Not overriding, append.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004167 vtable->Set<false>(actual_count, local_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004168 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004169 actual_count += 1;
4170 }
4171 }
4172 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004173 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004174 return false;
4175 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004176 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004177 CHECK_LE(actual_count, max_count);
4178 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004179 vtable.Assign(vtable->CopyOf(self, actual_count));
4180 if (UNLIKELY(vtable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004181 CHECK(self->IsExceptionPending()); // OOME.
4182 return false;
4183 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004184 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004185 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004186 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004187 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004188 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004189 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004190 ThrowClassFormatError(klass.Get(), "Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004191 return false;
4192 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004193 StackHandleScope<1> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004194 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004195 vtable(hs.NewHandle(AllocArtMethodArray(self, num_virtual_methods)));
4196 if (UNLIKELY(vtable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004197 CHECK(self->IsExceptionPending()); // OOME.
4198 return false;
4199 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004200 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004201 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004202 vtable->Set<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004203 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004204 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004205 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004206 }
4207 return true;
4208}
4209
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004210bool ClassLinker::LinkInterfaceMethods(Handle<mirror::Class> klass,
4211 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004212 Thread* const self = Thread::Current();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004213 Runtime* const runtime = Runtime::Current();
Jeff Hao88474b42013-10-23 16:24:40 -07004214 // Set the imt table to be all conflicts by default.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004215 klass->SetImTable(runtime->GetDefaultImt());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004216 size_t super_ifcount;
4217 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004218 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004219 } else {
4220 super_ifcount = 0;
4221 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07004222 uint32_t num_interfaces =
4223 interfaces.Get() == nullptr ? klass->NumDirectInterfaces() : interfaces->GetLength();
4224 size_t ifcount = super_ifcount + num_interfaces;
4225 for (size_t i = 0; i < num_interfaces; i++) {
4226 mirror::Class* interface =
4227 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4228 interfaces->Get(i);
4229 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004230 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004231 if (ifcount == 0) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004232 // Class implements no interfaces.
4233 DCHECK_EQ(klass->GetIfTableCount(), 0);
4234 DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004235 return true;
4236 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004237 if (ifcount == super_ifcount) {
4238 // Class implements same interfaces as parent, are any of these not marker interfaces?
4239 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004240 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Ian Rogers9bc81912012-10-11 21:43:36 -07004241 for (size_t i = 0; i < ifcount; ++i) {
4242 if (super_iftable->GetMethodArrayCount(i) > 0) {
4243 has_non_marker_interface = true;
4244 break;
4245 }
4246 }
4247 if (!has_non_marker_interface) {
4248 // Class just inherits marker interfaces from parent so recycle parent's iftable.
4249 klass->SetIfTable(super_iftable);
4250 return true;
4251 }
4252 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004253 StackHandleScope<4> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004254 Handle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
4255 if (UNLIKELY(iftable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004256 CHECK(self->IsExceptionPending()); // OOME.
4257 return false;
4258 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004259 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004260 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004261 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004262 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004263 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004264 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004265 }
4266 // Flatten the interface inheritance hierarchy.
4267 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004268 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004269 mirror::Class* interface =
Mathieu Chartierf8322842014-05-16 10:59:25 -07004270 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4271 interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004272 DCHECK(interface != NULL);
4273 if (!interface->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004274 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4275 PrettyDescriptor(klass.Get()).c_str(),
Mathieu Chartierf8322842014-05-16 10:59:25 -07004276 PrettyDescriptor(interface->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004277 return false;
4278 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004279 // Check if interface is already in iftable
4280 bool duplicate = false;
4281 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004282 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004283 if (existing_interface == interface) {
4284 duplicate = true;
4285 break;
4286 }
4287 }
4288 if (!duplicate) {
4289 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004290 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004291 // Add this interface's non-duplicate super-interfaces.
4292 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004293 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004294 bool super_duplicate = false;
4295 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004296 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004297 if (existing_interface == super_interface) {
4298 super_duplicate = true;
4299 break;
4300 }
4301 }
4302 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004303 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004304 }
4305 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004306 }
4307 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004308 // Shrink iftable in case duplicates were found
4309 if (idx < ifcount) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004310 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
4311 if (UNLIKELY(iftable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004312 CHECK(self->IsExceptionPending()); // OOME.
4313 return false;
4314 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004315 ifcount = idx;
4316 } else {
4317 CHECK_EQ(idx, ifcount);
4318 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004319 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004320
4321 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004322 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004323 return true;
4324 }
Jeff Hao88474b42013-10-23 16:24:40 -07004325 // Allocate imtable
4326 bool imtable_changed = false;
Ian Rogers700a4022014-05-19 16:49:03 -07004327 Handle<mirror::ObjectArray<mirror::ArtMethod>> imtable(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004328 hs.NewHandle(AllocArtMethodArray(self, mirror::Class::kImtSize)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004329 if (UNLIKELY(imtable.Get() == NULL)) {
Jeff Hao88474b42013-10-23 16:24:40 -07004330 CHECK(self->IsExceptionPending()); // OOME.
4331 return false;
4332 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004333 MethodHelper interface_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4334 MethodHelper vtable_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Brian Carlstromea46f952013-07-30 01:26:50 -07004335 std::vector<mirror::ArtMethod*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004336 for (size_t i = 0; i < ifcount; ++i) {
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004337 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004338 if (num_methods > 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004339 StackHandleScope<2> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004340 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004341 method_array(hs.NewHandle(AllocArtMethodArray(self, num_methods)));
4342 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004343 CHECK(self->IsExceptionPending()); // OOME.
4344 return false;
4345 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004346 iftable->SetMethodArray(i, method_array.Get());
Ian Rogers700a4022014-05-19 16:49:03 -07004347 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004348 hs.NewHandle(klass->GetVTableDuringLinking()));
Ian Rogers62d6c772013-02-27 08:32:07 -08004349 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004350 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004351 interface_mh.ChangeMethod(interface_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004352 int32_t k;
4353 // For each method listed in the interface's method list, find the
4354 // matching method in our class's method list. We want to favor the
4355 // subclass over the superclass, which just requires walking
4356 // back from the end of the vtable. (This only matters if the
4357 // superclass defines a private method and this class redefines
4358 // it -- otherwise it would use the same vtable slot. In .dex files
4359 // those don't end up in the virtual method table, so it shouldn't
4360 // matter which direction we go. We walk it backward anyway.)
4361 for (k = vtable->GetLength() - 1; k >= 0; --k) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004362 mirror::ArtMethod* vtable_method = vtable->Get(k);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004363 vtable_mh.ChangeMethod(vtable_method);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004364 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Elliott Hughes68243612013-02-22 17:16:07 -08004365 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004366 ThrowIllegalAccessError(
4367 klass.Get(),
4368 "Method '%s' implementing interface method '%s' is not public",
4369 PrettyMethod(vtable_method).c_str(),
4370 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004371 return false;
4372 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004373 method_array->Set<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004374 // Place method in imt if entry is empty, place conflict otherwise.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004375 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
Jeff Hao88474b42013-10-23 16:24:40 -07004376 if (imtable->Get(imt_index) == NULL) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004377 imtable->Set<false>(imt_index, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004378 imtable_changed = true;
4379 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004380 imtable->Set<false>(imt_index, runtime->GetImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -07004381 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004382 break;
4383 }
4384 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004385 if (k < 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004386 StackHandleScope<1> hs(self);
4387 auto miranda_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004388 for (mirror::ArtMethod* mir_method : miranda_list) {
4389 vtable_mh.ChangeMethod(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004390 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004391 miranda_method.Assign(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004392 break;
4393 }
4394 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004395 if (miranda_method.Get() == NULL) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004396 // Point the interface table at a phantom slot.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004397 miranda_method.Assign(down_cast<mirror::ArtMethod*>(interface_method->Clone(self)));
4398 if (UNLIKELY(miranda_method.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004399 CHECK(self->IsExceptionPending()); // OOME.
4400 return false;
4401 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004402 // TODO: If a methods move then the miranda_list may hold stale references.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004403 miranda_list.push_back(miranda_method.Get());
Ian Rogers9bc81912012-10-11 21:43:36 -07004404 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004405 method_array->Set<false>(j, miranda_method.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004406 }
4407 }
4408 }
4409 }
Jeff Hao88474b42013-10-23 16:24:40 -07004410 if (imtable_changed) {
4411 // Fill in empty entries in interface method table with conflict.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004412 mirror::ArtMethod* imt_conflict_method = runtime->GetImtConflictMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004413 for (size_t i = 0; i < mirror::Class::kImtSize; i++) {
Jeff Hao88474b42013-10-23 16:24:40 -07004414 if (imtable->Get(i) == NULL) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004415 imtable->Set<false>(i, imt_conflict_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004416 }
4417 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004418 klass->SetImTable(imtable.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004419 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004420 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004421 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07004422 int new_method_count = old_method_count + miranda_list.size();
Ian Rogersa436fde2013-08-27 23:34:06 -07004423 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4424 if (old_method_count == 0) {
4425 virtuals = AllocArtMethodArray(self, new_method_count);
4426 } else {
4427 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4428 }
4429 if (UNLIKELY(virtuals == NULL)) {
4430 CHECK(self->IsExceptionPending()); // OOME.
4431 return false;
4432 }
4433 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004434
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004435 StackHandleScope<1> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004436 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004437 hs.NewHandle(klass->GetVTableDuringLinking()));
4438 CHECK(vtable.Get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004439 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07004440 int new_vtable_count = old_vtable_count + miranda_list.size();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004441 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
4442 if (UNLIKELY(vtable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004443 CHECK(self->IsExceptionPending()); // OOME.
4444 return false;
4445 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004446 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004447 mirror::ArtMethod* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07004448 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07004449 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4450 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4451 klass->SetVirtualMethod(old_method_count + i, method);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004452 vtable->Set<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004453 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004454 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004455 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004456 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004457
Brian Carlstromea46f952013-07-30 01:26:50 -07004458 mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking();
Elliott Hughes4681c802011-09-25 18:04:37 -07004459 for (int i = 0; i < vtable->GetLength(); ++i) {
4460 CHECK(vtable->Get(i) != NULL);
4461 }
4462
4463// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
4464
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004465 return true;
4466}
4467
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004468bool ClassLinker::LinkInstanceFields(Handle<mirror::Class> klass) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004469 CHECK(klass.Get() != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004470 return LinkFields(klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004471}
4472
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004473bool ClassLinker::LinkStaticFields(Handle<mirror::Class> klass, size_t* class_size) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004474 CHECK(klass.Get() != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004475 return LinkFields(klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004476}
4477
Brian Carlstromdbc05252011-09-09 01:59:59 -07004478struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004479 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4480 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004481 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004482 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004483 NO_THREAD_SAFETY_ANALYSIS {
Brian Carlstromdbc05252011-09-09 01:59:59 -07004484 // First come reference fields, then 64-bit, and finally 32-bit
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004485 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
4486 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08004487 if (type1 != type2) {
4488 bool is_primitive1 = type1 != Primitive::kPrimNot;
4489 bool is_primitive2 = type2 != Primitive::kPrimNot;
Brian Carlstromf3632832014-05-20 15:36:53 -07004490 bool is64bit1 = is_primitive1 && (type1 == Primitive::kPrimLong ||
4491 type1 == Primitive::kPrimDouble);
4492 bool is64bit2 = is_primitive2 && (type2 == Primitive::kPrimLong ||
4493 type2 == Primitive::kPrimDouble);
Ian Rogersef7d42f2014-01-06 12:55:46 -08004494 int order1 = !is_primitive1 ? 0 : (is64bit1 ? 1 : 2);
4495 int order2 = !is_primitive2 ? 0 : (is64bit2 ? 1 : 2);
4496 if (order1 != order2) {
4497 return order1 < order2;
4498 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07004499 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07004500 // same basic group? then sort by string.
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004501 return strcmp(field1->GetName(), field2->GetName()) < 0;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004502 }
4503};
4504
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004505bool ClassLinker::LinkFields(Handle<mirror::Class> klass, bool is_static, size_t* class_size) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004506 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004507 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004508
Brian Carlstromea46f952013-07-30 01:26:50 -07004509 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004510 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004511
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004512 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07004513 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004514 if (is_static) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004515 uint32_t base = sizeof(mirror::Class); // Static fields come after the class.
4516 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
4517 // Static fields come after the embedded tables.
4518 base = mirror::Class::ComputeClassSize(true, klass->GetVTableDuringLinking()->GetLength(),
4519 0, 0, 0);
4520 }
4521 field_offset = MemberOffset(base);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004522 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004523 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004524 if (super_class != NULL) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004525 CHECK(super_class->IsResolved())
4526 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004527 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004528 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004529 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004530
Brian Carlstromf3632832014-05-20 15:36:53 -07004531 CHECK_EQ(num_fields == 0, fields == NULL) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004532
Brian Carlstromdbc05252011-09-09 01:59:59 -07004533 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07004534 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07004535 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004536 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004537 mirror::ArtField* f = fields->Get(i);
Brian Carlstromf3632832014-05-20 15:36:53 -07004538 CHECK(f != NULL) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004539 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004540 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07004541 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
4542 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07004543
4544 // References should be at the front.
4545 size_t current_field = 0;
4546 size_t num_reference_fields = 0;
4547 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004548 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004549 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004550 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004551 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004552 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004553 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07004554 grouped_and_sorted_fields.pop_front();
4555 num_reference_fields++;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004556 fields->Set<false>(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004557 field->SetOffset(field_offset);
4558 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004559 }
4560
4561 // Now we want to pack all of the double-wide fields together. If
4562 // we're not aligned, though, we want to shuffle one 32-bit field
4563 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07004564 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07004565 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004566 mirror::ArtField* field = grouped_and_sorted_fields[i];
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004567 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstromf3632832014-05-20 15:36:53 -07004568 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004569 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07004570 continue;
4571 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004572 fields->Set<false>(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004573 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004574 // drop the consumed field
4575 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
4576 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004577 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07004578 // whether we found a 32-bit field for padding or not, we advance
4579 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004580 }
4581
4582 // Alignment is good, shuffle any double-wide fields forward, and
4583 // finish assigning field offsets to all fields.
Brian Carlstromf3632832014-05-20 15:36:53 -07004584 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()))
4585 << PrettyClass(klass.Get());
Brian Carlstromdbc05252011-09-09 01:59:59 -07004586 while (!grouped_and_sorted_fields.empty()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004587 mirror::ArtField* field = grouped_and_sorted_fields.front();
Brian Carlstromdbc05252011-09-09 01:59:59 -07004588 grouped_and_sorted_fields.pop_front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004589 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstromf3632832014-05-20 15:36:53 -07004590 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004591 fields->Set<false>(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004592 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004593 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004594 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07004595 ? sizeof(uint64_t)
4596 : sizeof(uint32_t)));
4597 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004598 }
4599
Elliott Hughesadb460d2011-10-05 17:02:34 -07004600 // 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 -07004601 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07004602 // We know there are no non-reference fields in the Reference classes, and we know
4603 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07004604 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004605 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07004606 --num_reference_fields;
4607 }
4608
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004609 if (kIsDebugBuild) {
4610 // Make sure that all reference fields appear before
4611 // non-reference fields, and all double-wide fields are aligned.
4612 bool seen_non_ref = false;
4613 for (size_t i = 0; i < num_fields; i++) {
4614 mirror::ArtField* field = fields->Get(i);
4615 if (false) { // enable to debug field layout
4616 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004617 << " class=" << PrettyClass(klass.Get())
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004618 << " field=" << PrettyField(field)
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07004619 << " offset="
4620 << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004621 }
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004622 Primitive::Type type = field->GetTypeAsPrimitiveType();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004623 bool is_primitive = type != Primitive::kPrimNot;
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004624 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004625 strcmp("referent", field->GetName()) == 0) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004626 is_primitive = true; // We lied above, so we have to expect a lie here.
4627 }
4628 if (is_primitive) {
4629 if (!seen_non_ref) {
4630 seen_non_ref = true;
Brian Carlstromf3632832014-05-20 15:36:53 -07004631 DCHECK_EQ(num_reference_fields, i) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004632 }
4633 } else {
Brian Carlstromf3632832014-05-20 15:36:53 -07004634 DCHECK(!seen_non_ref) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004635 }
4636 }
4637 if (!seen_non_ref) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004638 DCHECK_EQ(num_fields, num_reference_fields) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004639 }
4640 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004641
4642 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004643 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004644 if (is_static) {
4645 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004646 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004647 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004648 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004649 if (!klass->IsVariableSize()) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004650 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor();
Mathieu Chartier79b4f382013-10-23 15:21:37 -07004651 size_t previous_size = klass->GetObjectSize();
4652 if (previous_size != 0) {
4653 // Make sure that we didn't originally have an incorrect size.
Brian Carlstromf3632832014-05-20 15:36:53 -07004654 CHECK_EQ(previous_size, size) << klass->GetDescriptor();
Mathieu Chartier79b4f382013-10-23 15:21:37 -07004655 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004656 klass->SetObjectSize(size);
4657 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004658 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004659 return true;
4660}
4661
4662// Set the bitmap of reference offsets, refOffsets, from the ifields
4663// list.
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004664void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004665 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004666 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004667 if (super_class != NULL) {
4668 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07004669 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004670 if (reference_offsets == CLASS_WALK_SUPER) {
4671 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004672 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004673 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004674 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004675 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004676}
4677
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004678void ClassLinker::CreateReferenceStaticOffsets(Handle<mirror::Class> klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004679 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004680}
4681
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004682void ClassLinker::CreateReferenceOffsets(Handle<mirror::Class> klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004683 uint32_t reference_offsets) {
4684 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004685 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
4686 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogersef7d42f2014-01-06 12:55:46 -08004687 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004688 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07004689 // All of the fields that contain object references are guaranteed
4690 // to be at the beginning of the fields list.
4691 for (size_t i = 0; i < num_reference_fields; ++i) {
4692 // Note that byte_offset is the offset from the beginning of
4693 // object, not the offset into instance data
Ian Rogersef7d42f2014-01-06 12:55:46 -08004694 mirror::ArtField* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004695 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004696 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
4697 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
4698 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07004699 CHECK_NE(new_bit, 0U);
4700 reference_offsets |= new_bit;
4701 } else {
4702 reference_offsets = CLASS_WALK_SUPER;
4703 break;
4704 }
4705 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004706 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004707 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004708 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004709 } else {
4710 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004711 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004712}
4713
Mathieu Chartier590fee92013-09-13 13:46:47 -07004714mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004715 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004716 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004717 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004718 if (resolved != NULL) {
4719 return resolved;
4720 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07004721 uint32_t utf16_length;
4722 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004723 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004724 dex_cache->SetResolvedString(string_idx, string);
4725 return string;
4726}
4727
Mathieu Chartier590fee92013-09-13 13:46:47 -07004728mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08004729 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004730 StackHandleScope<2> hs(Thread::Current());
4731 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
4732 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07004733 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
4734}
4735
4736mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004737 Handle<mirror::DexCache> dex_cache,
4738 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004739 DCHECK(dex_cache.Get() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004740 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004741 if (resolved == NULL) {
Ian Rogers98379392014-02-24 16:53:16 -08004742 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07004743 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08004744 resolved = FindClass(self, descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004745 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05004746 // TODO: we used to throw here if resolved's class loader was not the
4747 // boot class loader. This was to permit different classes with the
4748 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004749 dex_cache->SetResolvedType(type_idx, resolved);
4750 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08004751 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08004752 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08004753 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004754 StackHandleScope<1> hs(self);
4755 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08004756 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004757 DCHECK(resolved == NULL); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08004758 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08004759 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004760 self->GetException(NULL)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08004761 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004762 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004763 }
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07004764 DCHECK((resolved == NULL) || resolved->IsResolved() || resolved->IsErroneous())
4765 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004766 return resolved;
4767}
4768
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004769mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
4770 Handle<mirror::DexCache> dex_cache,
4771 Handle<mirror::ClassLoader> class_loader,
4772 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07004773 InvokeType type) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004774 DCHECK(dex_cache.Get() != NULL);
Ian Rogers08f753d2012-08-24 14:35:25 -07004775 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07004776 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004777 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004778 return resolved;
4779 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004780 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004781 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004782 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004783 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07004784 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004785 return NULL;
4786 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004787 // Scan using method_idx, this saves string compares but will only hit for matching dex
4788 // caches/files.
4789 switch (type) {
4790 case kDirect: // Fall-through.
4791 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004792 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004793 break;
4794 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004795 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Ian Rogers4c5b2652012-12-15 21:36:16 -08004796 DCHECK(resolved == NULL || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004797 break;
4798 case kSuper: // Fall-through.
4799 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004800 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004801 break;
4802 default:
4803 LOG(FATAL) << "Unreachable - invocation type: " << type;
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004804 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004805 if (resolved == NULL) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004806 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004807 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07004808 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07004809 switch (type) {
4810 case kDirect: // Fall-through.
4811 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08004812 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07004813 break;
4814 case kInterface:
4815 resolved = klass->FindInterfaceMethod(name, signature);
Ian Rogers4c5b2652012-12-15 21:36:16 -08004816 DCHECK(resolved == NULL || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004817 break;
4818 case kSuper: // Fall-through.
4819 case kVirtual:
4820 resolved = klass->FindVirtualMethod(name, signature);
4821 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004822 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004823 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004824 if (resolved != NULL) {
4825 // We found a method, check for incompatible class changes.
Ian Rogers87e552d2012-08-31 15:54:48 -07004826 if (resolved->CheckIncompatibleClassChange(type)) {
4827 resolved = NULL;
Ian Rogers08f753d2012-08-24 14:35:25 -07004828 }
4829 }
4830 if (resolved != NULL) {
4831 // Be a good citizen and update the dex cache to speed subsequent calls.
4832 dex_cache->SetResolvedMethod(method_idx, resolved);
4833 return resolved;
4834 } else {
jeffhaoc0228b82012-08-29 18:15:05 -07004835 // We failed to find the method which means either an access error, an incompatible class
4836 // change, or no such method. First try to find the method among direct and virtual methods.
Ian Rogers08f753d2012-08-24 14:35:25 -07004837 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07004838 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07004839 switch (type) {
4840 case kDirect:
4841 case kStatic:
4842 resolved = klass->FindVirtualMethod(name, signature);
jeffhaoc0228b82012-08-29 18:15:05 -07004843 break;
4844 case kInterface:
4845 case kVirtual:
4846 case kSuper:
4847 resolved = klass->FindDirectMethod(name, signature);
4848 break;
4849 }
4850
4851 // If we found something, check that it can be accessed by the referrer.
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004852 if (resolved != NULL && referrer.Get() != NULL) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004853 mirror::Class* methods_class = resolved->GetDeclaringClass();
4854 mirror::Class* referring_class = referrer->GetDeclaringClass();
jeffhaoc0228b82012-08-29 18:15:05 -07004855 if (!referring_class->CanAccess(methods_class)) {
Ian Rogers87e552d2012-08-31 15:54:48 -07004856 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
Vladimir Marko23a28212014-01-09 19:24:37 +00004857 resolved, type);
jeffhaoc0228b82012-08-29 18:15:05 -07004858 return NULL;
4859 } else if (!referring_class->CanAccessMember(methods_class,
4860 resolved->GetAccessFlags())) {
Ian Rogers87e552d2012-08-31 15:54:48 -07004861 ThrowIllegalAccessErrorMethod(referring_class, resolved);
jeffhaoc0228b82012-08-29 18:15:05 -07004862 return NULL;
4863 }
4864 }
4865
4866 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
4867 // methods and throw if we find the method there. If we find nothing, throw a NoSuchMethodError.
4868 switch (type) {
4869 case kDirect:
4870 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07004871 if (resolved != NULL) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004872 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07004873 } else {
4874 resolved = klass->FindInterfaceMethod(name, signature);
4875 if (resolved != NULL) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004876 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07004877 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08004878 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07004879 }
4880 }
4881 break;
4882 case kInterface:
Ian Rogers08f753d2012-08-24 14:35:25 -07004883 if (resolved != NULL) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004884 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07004885 } else {
4886 resolved = klass->FindVirtualMethod(name, signature);
4887 if (resolved != NULL) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004888 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07004889 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08004890 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07004891 }
4892 }
4893 break;
4894 case kSuper:
Ian Rogers62d6c772013-02-27 08:32:07 -08004895 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07004896 break;
4897 case kVirtual:
Ian Rogers08f753d2012-08-24 14:35:25 -07004898 if (resolved != NULL) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004899 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07004900 } else {
4901 resolved = klass->FindInterfaceMethod(name, signature);
4902 if (resolved != NULL) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004903 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07004904 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08004905 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07004906 }
4907 }
4908 break;
4909 }
4910 DCHECK(Thread::Current()->IsExceptionPending());
4911 return NULL;
4912 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004913}
4914
Mathieu Chartier590fee92013-09-13 13:46:47 -07004915mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004916 Handle<mirror::DexCache> dex_cache,
4917 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07004918 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004919 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07004920 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004921 if (resolved != NULL) {
4922 return resolved;
4923 }
4924 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004925 Thread* const self = Thread::Current();
4926 StackHandleScope<1> hs(self);
4927 Handle<mirror::Class> klass(
4928 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
4929 if (klass.Get() == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08004930 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004931 return NULL;
4932 }
4933
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004934 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004935 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004936 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004937 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004938 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004939
4940 if (resolved == NULL) {
4941 const char* name = dex_file.GetFieldName(field_id);
4942 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
4943 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004944 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004945 } else {
4946 resolved = klass->FindInstanceField(name, type);
4947 }
4948 if (resolved == NULL) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004949 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004950 return NULL;
4951 }
Ian Rogersb067ac22011-12-13 18:05:09 -08004952 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004953 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08004954 return resolved;
4955}
4956
Brian Carlstromea46f952013-07-30 01:26:50 -07004957mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004958 uint32_t field_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004959 Handle<mirror::DexCache> dex_cache,
4960 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004961 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07004962 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Ian Rogersb067ac22011-12-13 18:05:09 -08004963 if (resolved != NULL) {
4964 return resolved;
4965 }
4966 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004967 Thread* self = Thread::Current();
4968 StackHandleScope<1> hs(self);
4969 Handle<mirror::Class> klass(
4970 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
4971 if (klass.Get() == NULL) {
Ian Rogersb067ac22011-12-13 18:05:09 -08004972 DCHECK(Thread::Current()->IsExceptionPending());
4973 return NULL;
4974 }
4975
Ian Rogersdfb325e2013-10-30 01:00:44 -07004976 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
4977 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004978 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004979 resolved = mirror::Class::FindField(self, klass, name, type);
Ian Rogersb067ac22011-12-13 18:05:09 -08004980 if (resolved != NULL) {
4981 dex_cache->SetResolvedField(field_idx, resolved);
4982 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004983 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004984 }
4985 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07004986}
4987
Brian Carlstromea46f952013-07-30 01:26:50 -07004988const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004989 uint32_t* length) {
4990 mirror::Class* declaring_class = referrer->GetDeclaringClass();
4991 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07004992 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07004993 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08004994 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07004995}
4996
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004997void ClassLinker::DumpAllClasses(int flags) {
4998 if (dex_cache_image_class_lookup_required_) {
4999 MoveImageClassesToClassTable();
5000 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005001 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5002 // 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 -08005003 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005004 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005005 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005006 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
5007 mirror::Class* klass = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07005008 all_classes.push_back(klass);
Ian Rogers5d76c432011-10-31 21:42:49 -07005009 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005010 }
5011
5012 for (size_t i = 0; i < all_classes.size(); ++i) {
5013 all_classes[i]->DumpClass(std::cerr, flags);
5014 }
5015}
5016
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005017void ClassLinker::DumpForSigQuit(std::ostream& os) {
5018 if (dex_cache_image_class_lookup_required_) {
5019 MoveImageClassesToClassTable();
5020 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005021 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005022 os << "Loaded classes: " << class_table_.size() << " allocated classes\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005023}
5024
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005025size_t ClassLinker::NumLoadedClasses() {
5026 if (dex_cache_image_class_lookup_required_) {
5027 MoveImageClassesToClassTable();
5028 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005029 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005030 return class_table_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005031}
5032
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005033pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005034 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005035}
5036
5037pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005038 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005039}
5040
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005041void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005042 DCHECK(!init_done_);
5043
5044 DCHECK(klass != NULL);
5045 DCHECK(klass->GetClassLoader() == NULL);
5046
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005047 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005048 DCHECK(class_roots != NULL);
5049 DCHECK(class_roots->Get(class_root) == NULL);
5050 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005051}
5052
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005053} // namespace art