blob: e18c0d7b60069daf4b855bb48994d229ab26e1fb [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Brian Carlstromd601af82012-01-06 10:15:19 -080019#include <fcntl.h>
20#include <sys/file.h>
21#include <sys/stat.h>
Brian Carlstromdbc05252011-09-09 01:59:59 -070022#include <deque>
Ian Rogers700a4022014-05-19 16:49:03 -070023#include <memory>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070024#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070025#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070026#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070027
Elliott Hughes1aa246d2012-12-13 09:29:36 -080028#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080029#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010030#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080031#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080032#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080033#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000034#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080035#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070036#include "dex_file-inl.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070037#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070038#include "gc/accounting/card_table-inl.h"
39#include "gc/accounting/heap_bitmap.h"
40#include "gc/heap.h"
41#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070042#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070043#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070044#include "interpreter/interpreter.h"
Ian Rogers0571d352011-11-03 19:51:38 -070045#include "leb128.h"
Ian Rogerscb6b0f32014-08-12 02:30:58 -070046#include "method_helper-inl.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080047#include "oat.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070048#include "oat_file.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070049#include "object_lock.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070050#include "mirror/art_field-inl.h"
51#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "mirror/class.h"
53#include "mirror/class-inl.h"
54#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070055#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056#include "mirror/iftable-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057#include "mirror/object-inl.h"
58#include "mirror/object_array-inl.h"
59#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070060#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080061#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070062#include "mirror/string-inl.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080063#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070064#include "runtime.h"
Ian Rogers7655f292013-07-29 11:07:13 -070065#include "entrypoints/entrypoint_utils.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070066#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070067#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070068#include "handle_scope-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070069#include "thread.h"
70#include "utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080071#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070072#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070073
74namespace art {
75
Ian Rogers00f7d0e2012-07-19 15:28:27 -070076static void ThrowNoClassDefFoundError(const char* fmt, ...)
77 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070078 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070079static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070080 va_list args;
81 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -080082 Thread* self = Thread::Current();
83 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
84 self->ThrowNewExceptionV(throw_location, "Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080085 va_end(args);
86}
87
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080088static void ThrowEarlierClassFailure(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -070089 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5c599942012-06-13 16:45:05 -070090 // The class failed to initialize on a previous attempt, so we want to throw
91 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
92 // failed in verification, in which case v2 5.4.1 says we need to re-throw
93 // the previous error.
Ian Rogers87e552d2012-08-31 15:54:48 -070094 if (!Runtime::Current()->IsCompiler()) { // Give info if this occurs at runtime.
95 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
96 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -070097
Elliott Hughes5c599942012-06-13 16:45:05 -070098 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -080099 Thread* self = Thread::Current();
100 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700101 if (c->GetVerifyErrorClass() != NULL) {
102 // TODO: change the verifier to store an _instance_, with a useful detail message?
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700103 std::string temp;
104 self->ThrowNewException(throw_location, c->GetVerifyErrorClass()->GetDescriptor(&temp),
Mathieu Chartierf8322842014-05-16 10:59:25 -0700105 PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700106 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -0800107 self->ThrowNewException(throw_location, "Ljava/lang/NoClassDefFoundError;",
108 PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700109 }
110}
111
Ian Rogers62d6c772013-02-27 08:32:07 -0800112static void WrapExceptionInInitializer() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700113 Thread* self = Thread::Current();
114 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700115
116 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
117 CHECK(cause.get() != NULL);
118
119 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700120 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
121 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700122
Elliott Hughesa4f94742012-05-29 16:28:38 -0700123 // We only wrap non-Error exceptions; an Error can just be used as-is.
124 if (!is_error) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800125 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
126 self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;", NULL);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700127 }
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700128}
129
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800130static size_t Hash(const char* s) {
131 // This is the java.lang.String hashcode for convenience, not interoperability.
132 size_t hash = 0;
133 for (; *s != '\0'; ++s) {
134 hash = hash * 31 + *s;
135 }
136 return hash;
137}
138
Elliott Hughes418d20f2011-09-22 14:00:39 -0700139const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700140 "Ljava/lang/Class;",
141 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700142 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700143 "[Ljava/lang/Object;",
144 "Ljava/lang/String;",
Mathieu Chartier66f19252012-09-18 08:57:04 -0700145 "Ljava/lang/DexCache;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700146 "Ljava/lang/ref/Reference;",
Brian Carlstromea46f952013-07-30 01:26:50 -0700147 "Ljava/lang/reflect/ArtField;",
148 "Ljava/lang/reflect/ArtMethod;",
Ian Rogers466bb252011-10-14 03:29:56 -0700149 "Ljava/lang/reflect/Proxy;",
Mathieu Chartier66f19252012-09-18 08:57:04 -0700150 "[Ljava/lang/String;",
Brian Carlstromea46f952013-07-30 01:26:50 -0700151 "[Ljava/lang/reflect/ArtField;",
152 "[Ljava/lang/reflect/ArtMethod;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700153 "Ljava/lang/ClassLoader;",
Ian Rogers5167c972012-02-03 10:41:20 -0800154 "Ljava/lang/Throwable;",
jeffhao8cd6dda2012-02-22 10:15:34 -0800155 "Ljava/lang/ClassNotFoundException;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700156 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700157 "Z",
158 "B",
159 "C",
160 "D",
161 "F",
162 "I",
163 "J",
164 "S",
165 "V",
166 "[Z",
167 "[B",
168 "[C",
169 "[D",
170 "[F",
171 "[I",
172 "[J",
173 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700174 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700175};
176
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800177ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700178 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700179 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700180 dex_cache_image_class_lookup_required_(false),
181 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800182 class_roots_(nullptr),
183 array_iftable_(nullptr),
184 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700185 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800186 log_new_dex_caches_roots_(false),
187 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700188 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800189 portable_resolution_trampoline_(nullptr),
190 quick_resolution_trampoline_(nullptr),
191 portable_imt_conflict_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800192 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100193 quick_generic_jni_trampoline_(nullptr),
194 quick_to_interpreter_bridge_trampoline_(nullptr) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700195 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Ian Rogers98379392014-02-24 16:53:16 -0800196 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700197}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700198
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700199// To set a value for generic JNI. May be necessary in compiler tests.
200extern "C" void art_quick_generic_jni_trampoline(mirror::ArtMethod*);
Alex Light507e6182014-08-19 14:23:13 -0700201extern "C" void art_quick_resolution_trampoline(mirror::ArtMethod*);
202extern "C" void art_quick_imt_conflict_trampoline(mirror::ArtMethod*);
203extern "C" void art_quick_to_interpreter_bridge(mirror::ArtMethod*);
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700204
Alex Light507e6182014-08-19 14:23:13 -0700205void ClassLinker::InitWithoutImage(const std::vector<const DexFile*>& boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800206 VLOG(startup) << "ClassLinker::Init";
Alex Light507e6182014-08-19 14:23:13 -0700207 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700208
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700209 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700210
Elliott Hughes30646832011-10-13 16:59:46 -0700211 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700212 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700213 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700214 // 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 -0800215 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700216 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
217 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700218 heap->AllocNonMovableObject<true>(self, nullptr,
219 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700220 VoidFunctor()))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700221 CHECK(java_lang_Class.Get() != NULL);
222 mirror::Class::SetClassClass(java_lang_Class.Get());
223 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700224 if (kUseBakerOrBrooksReadBarrier) {
225 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800226 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700227 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800228 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800229 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700230
Elliott Hughes418d20f2011-09-22 14:00:39 -0700231 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700232 Handle<mirror::Class> class_array_class(hs.NewHandle(
233 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700234 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700235
Ian Rogers23435d02012-09-24 11:23:12 -0700236 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700237 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
238 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700239 CHECK(java_lang_Object.Get() != NULL);
Ian Rogers23435d02012-09-24 11:23:12 -0700240 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700241 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700242 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700243
Ian Rogers23435d02012-09-24 11:23:12 -0700244 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700245 Handle<mirror::Class> object_array_class(hs.NewHandle(
246 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700247 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700248
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700249 // Setup the char (primitive) class to be used for char[].
250 Handle<mirror::Class> char_class(hs.NewHandle(
251 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700252
Ian Rogers23435d02012-09-24 11:23:12 -0700253 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700254 Handle<mirror::Class> char_array_class(hs.NewHandle(
255 AllocClass(self, java_lang_Class.Get(),
256 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700257 char_array_class->SetComponentType(char_class.Get());
258 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700259
Ian Rogers23435d02012-09-24 11:23:12 -0700260 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700261 Handle<mirror::Class> java_lang_String(hs.NewHandle(
262 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700263 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700264 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700265 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400266
Fred Shih4ee7a662014-07-11 09:59:27 -0700267 // Setup Reference.
268 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
269 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
270 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
271 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
272 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
273
Ian Rogers23435d02012-09-24 11:23:12 -0700274 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700275 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
276 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
277 kClassRootsMax));
278 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700279 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
280 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
281 SetClassRoot(kClassArrayClass, class_array_class.Get());
282 SetClassRoot(kObjectArrayClass, object_array_class.Get());
283 SetClassRoot(kCharArrayClass, char_array_class.Get());
284 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700285 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700286
287 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700288 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
289 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
290 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
291 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
292 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
293 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
294 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
295 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700296
Ian Rogers23435d02012-09-24 11:23:12 -0700297 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700298 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700299
Ian Rogers23435d02012-09-24 11:23:12 -0700300 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700301 Handle<mirror::Class> int_array_class(hs.NewHandle(
302 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700303 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700304 mirror::IntArray::SetArrayClass(int_array_class.Get());
305 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700306
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700307 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700308
Ian Rogers52813c92012-10-11 11:50:38 -0700309 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700310 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
311 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700312 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700313 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700314 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700315
Brian Carlstromf3632832014-05-20 15:36:53 -0700316 // Constructor, Field, Method, and AbstractMethod are necessary so
317 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700318 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
319 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700320 CHECK(java_lang_reflect_ArtField.Get() != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700321 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700322 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700323 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700324 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700325
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700326 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
327 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700328 CHECK(java_lang_reflect_ArtMethod.Get() != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700329 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700330 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700331 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700332
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700333 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700334
335 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700336 Handle<mirror::Class> object_array_string(hs.NewHandle(
337 AllocClass(self, java_lang_Class.Get(),
338 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700339 object_array_string->SetComponentType(java_lang_String.Get());
340 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700341
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700342 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
343 AllocClass(self, java_lang_Class.Get(),
344 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700345 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
346 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700347
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700348 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
349 AllocClass(self, java_lang_Class.Get(),
350 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700351 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
352 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700353
Ian Rogers23435d02012-09-24 11:23:12 -0700354 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
355 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
356 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700357 CHECK_NE(0U, boot_class_path.size());
358 for (size_t i = 0; i != boot_class_path.size(); ++i) {
359 const DexFile* dex_file = boot_class_path[i];
360 CHECK(dex_file != NULL);
361 AppendToBootClassPath(*dex_file);
362 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700363
364 // now we can use FindSystemClass
365
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700366 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700367 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
368 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700369
Jeff Hao88474b42013-10-23 16:24:40 -0700370 // Create runtime resolution and imt conflict methods. Also setup the default imt.
371 Runtime* runtime = Runtime::Current();
372 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
373 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
374 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
375
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700376 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
377 // we do not need friend classes or a publicly exposed setter.
378 quick_generic_jni_trampoline_ = reinterpret_cast<void*>(art_quick_generic_jni_trampoline);
Alex Light507e6182014-08-19 14:23:13 -0700379 if (!runtime->IsCompiler()) {
380 // We need to set up the generic trampolines since we don't have an image.
381 quick_resolution_trampoline_ = reinterpret_cast<void*>(art_quick_resolution_trampoline);
382 quick_imt_conflict_trampoline_ = reinterpret_cast<void*>(art_quick_imt_conflict_trampoline);
383 quick_to_interpreter_bridge_trampoline_ = reinterpret_cast<void*>(art_quick_to_interpreter_bridge);
384 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700385
Mathieu Chartier66f19252012-09-18 08:57:04 -0700386 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700387 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800388 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700389 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700390 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700391 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800392 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700393 std::ostringstream os1, os2;
394 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
395 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
396 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
397 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700398 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800399 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700400 CHECK_EQ(java_lang_String.Get(), String_class);
401 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700402 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700403
Ian Rogers23435d02012-09-24 11:23:12 -0700404 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800405 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800406 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700407
Ian Rogers98379392014-02-24 16:53:16 -0800408 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800409 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700410
Ian Rogers98379392014-02-24 16:53:16 -0800411 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700412 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413
Ian Rogers98379392014-02-24 16:53:16 -0800414 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800415 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700416
Ian Rogers98379392014-02-24 16:53:16 -0800417 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700418 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700419
Ian Rogers98379392014-02-24 16:53:16 -0800420 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800421 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700422
Ian Rogers98379392014-02-24 16:53:16 -0800423 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800424 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700425
Ian Rogers98379392014-02-24 16:53:16 -0800426 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800427 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700428
Ian Rogers98379392014-02-24 16:53:16 -0800429 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700430 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700431
Ian Rogers98379392014-02-24 16:53:16 -0800432 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700433 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700434
Ian Rogers23435d02012-09-24 11:23:12 -0700435 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800436 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700437 CHECK(java_lang_Cloneable != NULL);
Ian Rogers98379392014-02-24 16:53:16 -0800438 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700439 CHECK(java_io_Serializable != NULL);
Ian Rogers23435d02012-09-24 11:23:12 -0700440 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
441 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700442 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700443 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700444 array_iftable->SetInterface(0, java_lang_Cloneable);
445 array_iftable->SetInterface(1, java_io_Serializable);
446 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700447
Ian Rogers23435d02012-09-24 11:23:12 -0700448 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700449 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
450 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
451 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
452 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700453 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700454 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800455 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700456 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700457
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700458 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800459 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700460 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700461
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700462 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800463 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700464 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700465
Brian Carlstromf3632832014-05-20 15:36:53 -0700466 mirror::Class* String_array_class =
467 FindSystemClass(self, class_roots_descriptors_[kJavaLangStringArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700468 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700469
Brian Carlstromea46f952013-07-30 01:26:50 -0700470 mirror::Class* Art_method_array_class =
Ian Rogers98379392014-02-24 16:53:16 -0800471 FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700472 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700473
Brian Carlstromea46f952013-07-30 01:26:50 -0700474 mirror::Class* Art_field_array_class =
Ian Rogers98379392014-02-24 16:53:16 -0800475 FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700476 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700477
Ian Rogers23435d02012-09-24 11:23:12 -0700478 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700479
Ian Rogers23435d02012-09-24 11:23:12 -0700480 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800481 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700482 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
483
Brian Carlstrom1f870082011-08-23 16:02:11 -0700484 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700485 // finish initializing Reference class
486 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
487 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
488 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
489 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
490 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700491 mirror::Class* java_lang_ref_FinalizerReference =
492 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700493 java_lang_ref_FinalizerReference->SetAccessFlags(
494 java_lang_ref_FinalizerReference->GetAccessFlags() |
495 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700496 mirror::Class* java_lang_ref_PhantomReference =
497 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700498 java_lang_ref_PhantomReference->SetAccessFlags(
499 java_lang_ref_PhantomReference->GetAccessFlags() |
500 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700501 mirror::Class* java_lang_ref_SoftReference =
502 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700503 java_lang_ref_SoftReference->SetAccessFlags(
504 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700505 mirror::Class* java_lang_ref_WeakReference =
506 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700507 java_lang_ref_WeakReference->SetAccessFlags(
508 java_lang_ref_WeakReference->GetAccessFlags() |
509 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700510
Ian Rogers23435d02012-09-24 11:23:12 -0700511 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800512 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700513 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700514 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
515
jeffhao8cd6dda2012-02-22 10:15:34 -0800516 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700517 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800518 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800519 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700520 SetClassRoot(kJavaLangClassNotFoundException,
521 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800522 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700523 SetClassRoot(kJavaLangStackTraceElementArrayClass,
524 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800525 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700526
Ian Rogers98379392014-02-24 16:53:16 -0800527 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700528
Brian Carlstroma004aa92012-02-08 18:05:09 -0800529 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700530}
531
Ian Rogers98379392014-02-24 16:53:16 -0800532void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800533 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700534
535 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700536 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700537 // as the types of the field can't be resolved prior to the runtime being
538 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800539 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700540 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800541 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800542
Brian Carlstromea46f952013-07-30 01:26:50 -0700543 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700544 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
545 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700546
Brian Carlstromea46f952013-07-30 01:26:50 -0700547 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700548 CHECK_STREQ(queue->GetName(), "queue");
549 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700550
Brian Carlstromea46f952013-07-30 01:26:50 -0700551 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700552 CHECK_STREQ(queueNext->GetName(), "queueNext");
553 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700554
Brian Carlstromea46f952013-07-30 01:26:50 -0700555 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700556 CHECK_STREQ(referent->GetName(), "referent");
557 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700558
Brian Carlstromea46f952013-07-30 01:26:50 -0700559 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700560 CHECK_STREQ(zombie->GetName(), "zombie");
561 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700562
Brian Carlstroma663ea52011-08-19 23:33:41 -0700563 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700564 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700565 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800566 mirror::Class* klass = GetClassRoot(class_root);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700567 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700568 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700569 // note SetClassRoot does additional validation.
570 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700571 }
572
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700573 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700574
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700575 // disable the slow paths in FindClass and CreatePrimitiveClass now
576 // that Object, Class, and Object[] are setup
577 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700578
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800579 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700580}
581
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700582void ClassLinker::RunRootClinits() {
583 Thread* self = Thread::Current();
584 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800585 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700586 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700587 StackHandleScope<1> hs(self);
588 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
589 EnsureInitialized(h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700590 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700591 }
592 }
593}
594
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700595bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800596 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000597 const char* oat_cache_filename,
598 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700599 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700600 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800601
Ian Rogers1d54e732013-05-02 21:10:01 -0700602 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800603 std::string boot_image_option("--boot-image=");
Alex Light507e6182014-08-19 14:23:13 -0700604 if (heap->GetImageSpace() == nullptr) {
605 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
606 // out of space anyway it might not matter.
607 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
608 "without an image.", dex_filename);
609 return false;
610 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700611 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800612
Brian Carlstrom6449c622014-02-10 23:48:36 -0800613 std::string dex_file_option("--dex-file=");
614 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800615
Brian Carlstrom6449c622014-02-10 23:48:36 -0800616 std::string oat_fd_option("--oat-fd=");
617 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800618
Brian Carlstrom6449c622014-02-10 23:48:36 -0800619 std::string oat_location_option("--oat-location=");
620 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800621
Brian Carlstrom6449c622014-02-10 23:48:36 -0800622 std::vector<std::string> argv;
623 argv.push_back(dex2oat);
624 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800625 argv.push_back("-classpath");
626 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800627 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800628
Ian Rogers8afeb852014-04-02 14:55:49 -0700629 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800630
Jeff Hao4a200f52014-04-01 14:58:49 -0700631 if (!Runtime::Current()->IsVerificationEnabled()) {
632 argv.push_back("--compiler-filter=verify-none");
633 }
634
Alex Light345c4b12014-07-18 14:57:04 -0700635 if (Runtime::Current()->MustRelocateIfPossible()) {
636 argv.push_back("--runtime-arg");
637 argv.push_back("-Xrelocate");
638 } else {
639 argv.push_back("--runtime-arg");
640 argv.push_back("-Xnorelocate");
641 }
642
Brian Carlstrom6449c622014-02-10 23:48:36 -0800643 if (!kIsTargetBuild) {
644 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700645 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700646
Brian Carlstrom6449c622014-02-10 23:48:36 -0800647 argv.push_back(boot_image_option);
648 argv.push_back(dex_file_option);
649 argv.push_back(oat_fd_option);
650 argv.push_back(oat_location_option);
651 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800652 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800653 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700654 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800655
656 return Exec(argv, error_msg);
jeffhao262bf462011-10-20 18:36:32 -0700657}
658
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700659const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700660 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800661 if (kIsDebugBuild) {
662 for (size_t i = 0; i < oat_files_.size(); ++i) {
663 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700664 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800665 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700666 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
667 oat_files_.push_back(oat_file);
668 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800669}
670
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700671OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
672 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700673 OatFile* oat_file = space->ReleaseOatFile();
674 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700675 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700676 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700677}
678
Brian Carlstromae826982011-11-09 01:33:42 -0800679const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800680 const char* dex_location = dex_file.GetLocation().c_str();
681 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700682 return FindOpenedOatFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800683}
684
Andreas Gampe833a4852014-05-21 18:46:59 -0700685const OatFile* ClassLinker::FindOpenedOatFile(const char* oat_location, const char* dex_location,
686 const uint32_t* const dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700687 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromae826982011-11-09 01:33:42 -0800688 for (size_t i = 0; i < oat_files_.size(); i++) {
689 const OatFile* oat_file = oat_files_[i];
690 DCHECK(oat_file != NULL);
Andreas Gampe833a4852014-05-21 18:46:59 -0700691
692 if (oat_location != nullptr) {
693 if (oat_file->GetLocation() != oat_location) {
694 continue;
695 }
696 }
697
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700698 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800699 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700700 false);
Brian Carlstroma004aa92012-02-08 18:05:09 -0800701 if (oat_dex_file != NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800702 return oat_file;
703 }
704 }
705 return NULL;
706}
707
Andreas Gampe833a4852014-05-21 18:46:59 -0700708static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file, const char* dex_location,
709 bool generated,
710 std::vector<std::string>* error_msgs,
711 std::vector<const DexFile*>* dex_files) {
712 if (oat_file == nullptr) {
713 return false;
714 }
715
716 size_t old_size = dex_files->size(); // To rollback on error.
717
718 bool success = true;
719 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100720 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700721 const char* next_name = next_name_str.c_str();
722
723 uint32_t dex_location_checksum;
724 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
725 std::string error_msg;
726 if (!DexFile::GetChecksum(next_name, dex_location_checksum_pointer, &error_msg)) {
727 DCHECK_EQ(false, i == 0 && generated);
728 dex_location_checksum_pointer = nullptr;
729 }
730
731 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
732
733 if (oat_dex_file == nullptr) {
734 if (i == 0 && generated) {
735 std::string error_msg;
736 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
737 " file'%s'", dex_location, dex_location_checksum,
738 oat_file->GetLocation().c_str());
739 error_msgs->push_back(error_msg);
740 }
741 break; // Not found, done.
742 }
743
744 // Checksum test. Test must succeed when generated.
745 success = !generated;
746 if (dex_location_checksum_pointer != nullptr) {
747 success = dex_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
748 }
749
750 if (success) {
751 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
752 if (dex_file == nullptr) {
753 success = false;
754 error_msgs->push_back(error_msg);
755 } else {
756 dex_files->push_back(dex_file);
757 }
758 }
759
760 // When we generated the file, we expect success, or something is terribly wrong.
761 CHECK_EQ(false, generated && !success)
762 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
763 << std::hex << " dex_location_checksum=" << dex_location_checksum
764 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
765 }
766
767 if (dex_files->size() == old_size) {
768 success = false; // We did not even find classes.dex
769 }
770
771 if (success) {
772 return true;
773 } else {
774 // Free all the dex files we have loaded.
775 auto it = dex_files->begin() + old_size;
776 auto it_end = dex_files->end();
777 for (; it != it_end; it++) {
778 delete *it;
779 }
780 dex_files->erase(dex_files->begin() + old_size, it_end);
781
782 return false;
783 }
784}
785
786// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
787// complicates the loading process, as we should not use an iterative loading process, because that
788// would register the oat file and dex files that come before the broken one. Instead, check all
789// multidex ahead of time.
790bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
791 std::vector<std::string>* error_msgs,
792 std::vector<const DexFile*>* dex_files) {
793 // 1) Check whether we have an open oat file.
794 // This requires a dex checksum, use the "primary" one.
795 uint32_t dex_location_checksum;
796 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
797 bool have_checksum = true;
798 std::string checksum_error_msg;
799 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
800 dex_location_checksum_pointer = nullptr;
801 have_checksum = false;
802 }
803
804 bool needs_registering = false;
805
806 std::unique_ptr<const OatFile> open_oat_file(FindOpenedOatFile(oat_location, dex_location,
807 dex_location_checksum_pointer));
808
809 // 2) If we do not have an open one, maybe there's one on disk already.
810
811 // In case the oat file is not open, we play a locking game here so
812 // that if two different processes race to load and register or generate
813 // (or worse, one tries to open a partial generated file) we will be okay.
814 // This is actually common with apps that use DexClassLoader to work
815 // around the dex method reference limit and that have a background
816 // service running in a separate process.
817 ScopedFlock scoped_flock;
818
819 if (open_oat_file.get() == nullptr) {
820 if (oat_location != nullptr) {
821 // Can only do this if we have a checksum, else error.
822 if (!have_checksum) {
823 error_msgs->push_back(checksum_error_msg);
824 return false;
825 }
826
827 std::string error_msg;
828
829 // We are loading or creating one in the future. Time to set up the file lock.
830 if (!scoped_flock.Init(oat_location, &error_msg)) {
831 error_msgs->push_back(error_msg);
832 return false;
833 }
834
Alex Lighta59dd802014-07-02 16:28:08 -0700835 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700836 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
837 oat_location, &error_msg));
838
839 if (open_oat_file.get() == nullptr) {
840 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
841 dex_location, oat_location, error_msg.c_str());
842 VLOG(class_linker) << compound_msg;
843 error_msgs->push_back(compound_msg);
844 }
845 } else {
846 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100847 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700848 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
849 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100850 kRuntimeISA, error_msgs,
851 &obsolete_file_cleanup_failed));
852 // There's no point in going forward and eventually try to regenerate the
853 // file if we couldn't remove the obsolete one. Mostly likely we will fail
854 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100855 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
856 if (obsolete_file_cleanup_failed) {
857 return false;
858 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700859 }
860 needs_registering = true;
861 }
862
863 // 3) If we have an oat file, check all contained multidex files for our dex_location.
864 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
865 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location, false, error_msgs,
866 dex_files);
867 if (success) {
868 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
869 if (needs_registering) {
870 // We opened the oat file, so we must register it.
871 RegisterOatFile(oat_file);
872 }
Alex Light0a112bb2014-08-14 14:16:26 -0700873 // If the file isn't executable we failed patchoat but did manage to get the dex files.
874 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700875 } else {
876 if (needs_registering) {
877 // We opened it, delete it.
878 open_oat_file.reset();
879 } else {
880 open_oat_file.release(); // Do not delete open oat files.
881 }
882 }
883
884 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
885
886 // Need a checksum, fail else.
887 if (!have_checksum) {
888 error_msgs->push_back(checksum_error_msg);
889 return false;
890 }
891
892 // Look in cache location if no oat_location is given.
893 std::string cache_location;
894 if (oat_location == nullptr) {
895 // Use the dalvik cache.
896 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
897 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
898 oat_location = cache_location.c_str();
899 }
900
Alex Light507e6182014-08-19 14:23:13 -0700901 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -0700902 // Definitely need to lock now.
903 if (!scoped_flock.HasFile()) {
904 std::string error_msg;
905 if (!scoped_flock.Init(oat_location, &error_msg)) {
906 error_msgs->push_back(error_msg);
Alex Light507e6182014-08-19 14:23:13 -0700907 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -0700908 }
909 }
910
Alex Light507e6182014-08-19 14:23:13 -0700911 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray9c290012014-07-22 10:48:00 +0100912 // Create the oat file.
913 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
914 oat_location, error_msgs));
915 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700916
917 // Failed, bail.
918 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray9c290012014-07-22 10:48:00 +0100919 std::string error_msg;
920 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
921 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
922 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -0700923 return false;
924 }
925
926 // Try to load again, but stronger checks.
927 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location, true, error_msgs,
928 dex_files);
929 if (success) {
930 RegisterOatFile(open_oat_file.release());
931 return true;
932 } else {
933 return false;
934 }
935}
936
937const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
938 uint32_t dex_location_checksum,
939 const char* oat_location,
940 std::string* error_msg) {
Ian Rogers700a4022014-05-19 16:49:03 -0700941 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, NULL,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700942 !Runtime::Current()->IsCompiler(),
943 error_msg));
944 if (oat_file.get() == nullptr) {
945 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
946 error_msg->c_str());
947 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800948 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700949 Runtime* runtime = Runtime::Current();
950 const ImageHeader& image_header = runtime->GetHeap()->GetImageSpace()->GetImageHeader();
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700951 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
952 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
953 if (expected_image_oat_checksum != actual_image_oat_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700954 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
955 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
956 actual_image_oat_checksum);
957 return nullptr;
Brian Carlstrom28db0122012-10-18 16:20:41 -0700958 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700959
Ian Rogersef7d42f2014-01-06 12:55:46 -0800960 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700961 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
962 if (expected_image_oat_offset != actual_image_oat_offset) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800963 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
964 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700965 actual_image_oat_offset);
966 return nullptr;
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700967 }
Alex Lighta59dd802014-07-02 16:28:08 -0700968 int32_t expected_patch_delta = image_header.GetPatchDelta();
969 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
970 if (expected_patch_delta != actual_patch_delta) {
971 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
972 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
973 return nullptr;
974 }
Vladimir Marko64e7ac02014-05-01 15:43:47 +0100975 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
976 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700977 if (oat_dex_file == nullptr) {
978 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
979 dex_location);
980 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800981 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700982 uint32_t expected_dex_checksum = dex_location_checksum;
983 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
984 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700985 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
986 "found 0x%x", oat_location, expected_dex_checksum,
987 actual_dex_checksum);
988 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800989 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700990 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
991 if (dex_file.get() != nullptr) {
992 return oat_file.release();
993 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700994 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700995 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700996}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700997
Andreas Gampe833a4852014-05-21 18:46:59 -0700998const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
999 int fd, const char* oat_location,
1000 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001001 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001002 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001003 std::string error_msg;
1004 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001005 CHECK(!error_msg.empty());
1006 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001007 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001008 }
Ian Rogers700a4022014-05-19 16:49:03 -07001009 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, NULL,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001010 !Runtime::Current()->IsCompiler(),
1011 &error_msg));
1012 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001013 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1014 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001015 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001016 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001017 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001018
1019 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001020}
1021
Alex Light345c4b12014-07-18 14:57:04 -07001022bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1023 const InstructionSet instruction_set) {
1024 Runtime* runtime = Runtime::Current();
1025 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light507e6182014-08-19 14:23:13 -07001026 if (image_space == nullptr) {
1027 return false;
1028 }
Alex Light345c4b12014-07-18 14:57:04 -07001029 uint32_t image_oat_checksum = 0;
1030 if (instruction_set == kRuntimeISA) {
1031 const ImageHeader& image_header = image_space->GetImageHeader();
1032 image_oat_checksum = image_header.GetOatChecksum();
1033 } else {
1034 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1035 image_space->GetImageLocation().c_str(), instruction_set));
1036 image_oat_checksum = image_header->GetOatChecksum();
1037 }
1038 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1039}
1040
1041bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1042 const InstructionSet instruction_set,
1043 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001044 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001045 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light507e6182014-08-19 14:23:13 -07001046 if (image_space == nullptr) {
1047 *error_msg = "No image space for verification against";
1048 return false;
1049 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001050
1051 // If the requested instruction set is the same as the current runtime,
1052 // we can use the checksums directly. If it isn't, we'll have to read the
1053 // image header from the image for the right instruction set.
1054 uint32_t image_oat_checksum = 0;
1055 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001056 int32_t image_patch_delta = 0;
1057 if (instruction_set == Runtime::Current()->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001058 const ImageHeader& image_header = image_space->GetImageHeader();
1059 image_oat_checksum = image_header.GetOatChecksum();
1060 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001061 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001062 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001063 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001064 image_space->GetImageLocation().c_str(), instruction_set));
1065 image_oat_checksum = image_header->GetOatChecksum();
1066 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001067 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001068 }
1069 const OatHeader& oat_header = oat_file->GetOatHeader();
Alex Light345c4b12014-07-18 14:57:04 -07001070 bool ret = ((oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum)
1071 && (oat_header.GetImagePatchDelta() == image_patch_delta)
1072 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin));
1073 if (!ret) {
1074 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1075 oat_file->GetLocation().c_str(),
1076 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1077 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1078 oat_file->GetOatHeader().GetImagePatchDelta(),
1079 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1080 }
1081 return ret;
1082}
1083
1084bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1085 const char* dex_location,
1086 uint32_t dex_location_checksum,
1087 const InstructionSet instruction_set,
1088 std::string* error_msg) {
1089 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1090 return false;
1091 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001092
Brian Carlstromf3632832014-05-20 15:36:53 -07001093 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1094 &dex_location_checksum);
Brian Carlstromafe25512012-06-27 17:02:58 -07001095 if (oat_dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001096 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1097 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Brian Carlstromafe25512012-06-27 17:02:58 -07001098 std::vector<const OatFile::OatDexFile*> oat_dex_files = oat_file->GetOatDexFiles();
1099 for (size_t i = 0; i < oat_dex_files.size(); i++) {
1100 const OatFile::OatDexFile* oat_dex_file = oat_dex_files[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001101 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s'",
1102 oat_file->GetLocation().c_str(),
1103 oat_dex_file->GetDexFileLocation().c_str());
Brian Carlstromafe25512012-06-27 17:02:58 -07001104 }
1105 return false;
1106 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001107
Alex Light345c4b12014-07-18 14:57:04 -07001108 if (dex_location_checksum != oat_dex_file->GetDexFileLocationChecksum()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001109 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x) with '%s' (0x%x)",
1110 oat_file->GetLocation().c_str(),
1111 oat_dex_file->GetDexFileLocationChecksum(),
1112 dex_location, dex_location_checksum);
Alex Light345c4b12014-07-18 14:57:04 -07001113 return false;
Brian Carlstromafe25512012-06-27 17:02:58 -07001114 }
Alex Light345c4b12014-07-18 14:57:04 -07001115 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001116}
1117
Alex Lighta59dd802014-07-02 16:28:08 -07001118bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1119 const char* dex_location,
1120 std::string* error_msg) {
1121 CHECK(oat_file != nullptr);
1122 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001123 std::unique_ptr<const DexFile> dex_file;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001124 uint32_t dex_location_checksum;
1125 if (!DexFile::GetChecksum(dex_location, &dex_location_checksum, error_msg)) {
1126 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1127 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1128 // directory.
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001129 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, NULL);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001130 if (oat_dex_file == nullptr) {
1131 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001132 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001133 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001134 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001135 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001136 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001137 } else {
Alex Light345c4b12014-07-18 14:57:04 -07001138 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, dex_location_checksum,
1139 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001140 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001141 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001142 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001143 dex_file.reset(oat_file->GetOatDexFile(dex_location,
1144 &dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001145 }
Alex Lighta59dd802014-07-02 16:28:08 -07001146 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001147}
1148
Andreas Gampe833a4852014-05-21 18:46:59 -07001149const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001150 const char* dex_location,
1151 const uint32_t* const dex_location_checksum,
1152 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001153 std::vector<std::string>* error_msgs,
1154 bool* obsolete_file_cleanup_failed) {
1155 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001156 bool already_opened = false;
1157 std::string dex_location_str(dex_location);
1158 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1159 &already_opened,
1160 obsolete_file_cleanup_failed,
1161 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001162 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001163 if (oat_file.get() == nullptr) {
1164 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1165 dex_location));
1166 return nullptr;
Alex Light0a112bb2014-08-14 14:16:26 -07001167 } else if (oat_file->IsExecutable() &&
1168 !VerifyOatWithDexFile(oat_file.get(), dex_location, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001169 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1170 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001171 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001172 return nullptr;
Alex Light0a112bb2014-08-14 14:16:26 -07001173 } else if (!oat_file->IsExecutable() &&
Alex Lightfb777592014-08-22 17:49:35 -07001174 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light0a112bb2014-08-14 14:16:26 -07001175 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1176 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1177 "dex location '%s'. Image checksum incorrect.",
1178 oat_file->GetLocation().c_str(), dex_location));
1179 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001180 } else {
1181 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001182 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001183}
1184
Brian Carlstromae826982011-11-09 01:33:42 -08001185const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001186 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001187 for (size_t i = 0; i < oat_files_.size(); i++) {
1188 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001189 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001190 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001191 return oat_file;
1192 }
1193 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001194 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001195}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001196
Alex Lighta59dd802014-07-02 16:28:08 -07001197const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1198 InstructionSet isa,
1199 bool *already_opened,
1200 bool *obsolete_file_cleanup_failed,
1201 std::vector<std::string>* error_msgs) {
1202 // Find out if we've already opened the file
1203 const OatFile* ret = nullptr;
1204 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1205 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1206 if (ret != nullptr) {
1207 *already_opened = true;
1208 return ret;
1209 }
1210
1211 std::string dalvik_cache;
1212 bool have_android_data = false;
1213 bool have_dalvik_cache = false;
1214 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
1215 &have_android_data, &have_dalvik_cache);
1216 std::string cache_filename;
1217 if (have_dalvik_cache) {
1218 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1219 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1220 if (ret != nullptr) {
1221 *already_opened = true;
1222 return ret;
1223 }
1224 } else {
1225 // If we need to relocate we should just place odex back where it started.
1226 cache_filename = odex_filename;
1227 }
1228
1229 ret = nullptr;
1230
1231 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1232 //
1233 // Now we do the following:
1234 // 1) Try and open the odex version
1235 // 2) If present, checksum-verified & relocated correctly return it
1236 // 3) Close the odex version to free up its address space.
1237 // 4) Try and open the cache version
1238 // 5) If present, checksum-verified & relocated correctly return it
1239 // 6) Close the cache version to free up its address space.
1240 // 7) If we should relocate:
1241 // a) If we have opened and checksum-verified the odex version relocate it to
1242 // 'cache_filename' and return it
1243 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1244 // it. This should not happen often (I think only the run-test's will hit this case).
1245 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1246 // this point.
1247 // 9) Return nullptr
1248
1249 *already_opened = false;
1250 const Runtime* runtime = Runtime::Current();
1251 CHECK(runtime != nullptr);
1252 bool executable = !runtime->IsCompiler();
1253
1254 std::string odex_error_msg;
1255 bool should_patch_system = false;
1256 bool odex_checksum_verified = false;
Alex Lightfb777592014-08-22 17:49:35 -07001257 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001258 {
1259 // There is a high probability that these both these oat files map similar/the same address
1260 // spaces so we must scope them like this so they each gets its turn.
1261 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, NULL,
1262 executable, &odex_error_msg));
1263 if (odex_oat_file.get() != nullptr && CheckOatFile(odex_oat_file.get(), isa,
1264 &odex_checksum_verified,
1265 &odex_error_msg)) {
1266 error_msgs->push_back(odex_error_msg);
1267 return odex_oat_file.release();
Alex Lightfb777592014-08-22 17:49:35 -07001268 } else {
1269 if (odex_checksum_verified) {
1270 // We can just relocate
1271 should_patch_system = true;
1272 odex_error_msg = "Image Patches are incorrect";
1273 }
1274 if (odex_oat_file.get() != nullptr) {
1275 have_system_odex = true;
1276 }
Alex Lighta59dd802014-07-02 16:28:08 -07001277 }
1278 }
1279
Alex Lighta59dd802014-07-02 16:28:08 -07001280 std::string cache_error_msg;
1281 bool should_patch_cache = false;
1282 bool cache_checksum_verified = false;
1283 if (have_dalvik_cache) {
1284 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, NULL,
1285 executable, &cache_error_msg));
1286 if (cache_oat_file.get() != nullptr && CheckOatFile(cache_oat_file.get(), isa,
1287 &cache_checksum_verified,
1288 &cache_error_msg)) {
1289 error_msgs->push_back(cache_error_msg);
1290 return cache_oat_file.release();
1291 } else if (cache_checksum_verified) {
1292 // We can just relocate
1293 should_patch_cache = true;
1294 cache_error_msg = "Image Patches are incorrect";
1295 }
1296 } else if (have_android_data) {
1297 // dalvik_cache does not exist but android data does. This means we should be able to create
1298 // it, so we should try.
1299 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1300 }
1301
1302 ret = nullptr;
1303 std::string error_msg;
1304 if (runtime->CanRelocate()) {
1305 // Run relocation
Alex Light507e6182014-08-19 14:23:13 -07001306 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1307 if (space != nullptr) {
1308 const std::string& image_location = space->GetImageLocation();
1309 if (odex_checksum_verified && should_patch_system) {
1310 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1311 } else if (cache_checksum_verified && should_patch_cache) {
1312 CHECK(have_dalvik_cache);
1313 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1314 }
Alex Lightfb777592014-08-22 17:49:35 -07001315 } else if (have_system_odex) {
1316 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001317 }
1318 }
1319 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1320 // implicitly: were able to fine where the cached version is but we were unable to use it,
1321 // either as a destination for relocation or to open a file. We should delete it if it is
1322 // there.
1323 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1324 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1325 "searching for dex file %s: %s",
1326 cache_filename.c_str(), dex_location.c_str(),
1327 strerror(errno));
1328 error_msgs->push_back(rm_error_msg);
1329 VLOG(class_linker) << rm_error_msg;
1330 // Let the caller know that we couldn't remove the obsolete file.
1331 // This is a good indication that further writes may fail as well.
1332 *obsolete_file_cleanup_failed = true;
1333 }
1334 }
1335 if (ret == nullptr) {
1336 VLOG(class_linker) << error_msg;
1337 error_msgs->push_back(error_msg);
1338 std::string relocation_msg;
1339 if (runtime->CanRelocate()) {
1340 relocation_msg = StringPrintf(" and relocation failed");
1341 }
1342 if (have_dalvik_cache && cache_checksum_verified) {
1343 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1344 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1345 cache_filename.c_str(), cache_error_msg.c_str(),
1346 relocation_msg.c_str());
1347 } else {
1348 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1349 "dalvik_cache availible)%s.", odex_filename.c_str(),
1350 odex_error_msg.c_str(), relocation_msg.c_str());
1351 }
1352 VLOG(class_linker) << error_msg;
1353 error_msgs->push_back(error_msg);
1354 }
1355 return ret;
1356}
1357
Alex Light0a112bb2014-08-14 14:16:26 -07001358const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1359 InstructionSet isa,
1360 std::string* error_msg) {
1361 // We open it non-executable
1362 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, NULL, false, error_msg));
1363 if (output.get() == nullptr) {
1364 return nullptr;
1365 }
Alex Lightfb777592014-08-22 17:49:35 -07001366 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1367 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light0a112bb2014-08-14 14:16:26 -07001368 return output.release();
1369 } else {
1370 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1371 oat_path.c_str());
1372 return nullptr;
1373 }
1374}
1375
Alex Lighta59dd802014-07-02 16:28:08 -07001376const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1377 const std::string& output_oat,
1378 const std::string& image_location,
1379 InstructionSet isa,
1380 std::string* error_msg) {
Alex Light507e6182014-08-19 14:23:13 -07001381 if (!Runtime::Current()->GetHeap()->HasImageSpace()) {
1382 // We don't have an image space so there is no point in trying to patchoat.
1383 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1384 << "running without an image. Attempting to use oat file for interpretation.";
1385 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1386 }
Alex Light0a112bb2014-08-14 14:16:26 -07001387 if (!Runtime::Current()->IsDex2OatEnabled()) {
1388 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1389 // input_oat but make sure we only do interpretation on it's dex files.
1390 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1391 << "disabled. Attempting to use oat file for interpretation";
1392 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1393 }
Alex Lighta59dd802014-07-02 16:28:08 -07001394 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
1395 std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
1396
1397 std::string isa_arg("--instruction-set=");
1398 isa_arg += GetInstructionSetString(isa);
1399 std::string input_oat_filename_arg("--input-oat-file=");
1400 input_oat_filename_arg += input_oat;
1401 std::string output_oat_filename_arg("--output-oat-file=");
1402 output_oat_filename_arg += output_oat;
1403 std::string patched_image_arg("--patched-image-location=");
1404 patched_image_arg += image_location;
1405
1406 std::vector<std::string> argv;
1407 argv.push_back(patchoat);
1408 argv.push_back(isa_arg);
1409 argv.push_back(input_oat_filename_arg);
1410 argv.push_back(output_oat_filename_arg);
1411 argv.push_back(patched_image_arg);
1412
1413 std::string command_line(Join(argv, ' '));
1414 LOG(INFO) << "Relocate Oat File: " << command_line;
1415 bool success = Exec(argv, error_msg);
1416 if (success) {
1417 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, NULL,
1418 !Runtime::Current()->IsCompiler(), error_msg));
1419 bool checksum_verified = false;
1420 if (output.get() != nullptr && CheckOatFile(output.get(), isa, &checksum_verified, error_msg)) {
1421 return output.release();
1422 } else if (output.get() != nullptr) {
1423 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1424 "but output file '%s' failed verifcation: %s",
1425 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1426 } else {
1427 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1428 "but was unable to open output file '%s': %s",
1429 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1430 }
Alex Light0a112bb2014-08-14 14:16:26 -07001431 } else if (!Runtime::Current()->IsCompiler()) {
1432 // patchoat failed which means we probably don't have enough room to place the output oat file,
1433 // instead of failing we should just run the interpreter from the dex files in the input oat.
1434 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1435 << "for interpretation. patchoat failure was: " << *error_msg;
1436 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001437 } else {
1438 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1439 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1440 error_msg->c_str());
1441 }
1442 return nullptr;
1443}
1444
1445int32_t ClassLinker::GetRequiredDelta(const OatFile* oat_file, InstructionSet isa) {
1446 Runtime* runtime = Runtime::Current();
1447 int32_t real_patch_delta;
1448 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light507e6182014-08-19 14:23:13 -07001449 CHECK(image_space != nullptr);
Alex Lighta59dd802014-07-02 16:28:08 -07001450 if (isa == Runtime::Current()->GetInstructionSet()) {
1451 const ImageHeader& image_header = image_space->GetImageHeader();
1452 real_patch_delta = image_header.GetPatchDelta();
1453 } else {
1454 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1455 image_space->GetImageLocation().c_str(), isa));
1456 real_patch_delta = image_header->GetPatchDelta();
1457 }
1458 const OatHeader& oat_header = oat_file->GetOatHeader();
1459 return real_patch_delta - oat_header.GetImagePatchDelta();
1460}
1461
1462bool ClassLinker::CheckOatFile(const OatFile* oat_file, InstructionSet isa,
1463 bool* checksum_verified,
1464 std::string* error_msg) {
1465 std::string compound_msg("Oat file failed to verify: ");
1466 Runtime* runtime = Runtime::Current();
1467 uint32_t real_image_checksum;
1468 void* real_image_oat_offset;
1469 int32_t real_patch_delta;
1470 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light507e6182014-08-19 14:23:13 -07001471 if (image_space == nullptr) {
1472 *error_msg = "No image space present";
1473 return false;
1474 }
Alex Lighta59dd802014-07-02 16:28:08 -07001475 if (isa == Runtime::Current()->GetInstructionSet()) {
1476 const ImageHeader& image_header = image_space->GetImageHeader();
1477 real_image_checksum = image_header.GetOatChecksum();
1478 real_image_oat_offset = image_header.GetOatDataBegin();
1479 real_patch_delta = image_header.GetPatchDelta();
1480 } else {
1481 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1482 image_space->GetImageLocation().c_str(), isa));
1483 real_image_checksum = image_header->GetOatChecksum();
1484 real_image_oat_offset = image_header->GetOatDataBegin();
1485 real_patch_delta = image_header->GetPatchDelta();
1486 }
1487
1488 const OatHeader& oat_header = oat_file->GetOatHeader();
1489
1490 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1491 *checksum_verified = oat_image_checksum == real_image_checksum;
1492 if (!*checksum_verified) {
1493 compound_msg += StringPrintf(" Oat Image Checksum Incorrect (expected 0x%x, recieved 0x%x)",
1494 real_image_checksum, oat_image_checksum);
1495 }
1496
1497 void* oat_image_oat_offset =
1498 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1499 bool offset_verified = oat_image_oat_offset == real_image_oat_offset;
1500 if (!offset_verified) {
1501 compound_msg += StringPrintf(" Oat Image oat offset incorrect (expected 0x%p, recieved 0x%p)",
1502 real_image_oat_offset, oat_image_oat_offset);
1503 }
1504
1505 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1506 bool patch_delta_verified = oat_patch_delta == real_patch_delta;
1507 if (!patch_delta_verified) {
1508 compound_msg += StringPrintf(" Oat image patch delta incorrect (expected 0x%x, recieved 0x%x)",
1509 real_patch_delta, oat_patch_delta);
1510 }
1511
1512 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
1513 if (ret) {
1514 *error_msg = compound_msg;
1515 }
1516 return ret;
1517}
1518
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001519const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1520 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001521 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001522 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001523 return oat_file;
1524 }
1525
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001526 oat_file = OatFile::Open(oat_location, oat_location, NULL, !Runtime::Current()->IsCompiler(),
1527 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001528 if (oat_file == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -08001529 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001530 }
1531 return oat_file;
1532}
1533
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001534static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
Ian Rogers848871b2013-08-05 10:56:33 -07001535 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001536 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1537
Ian Rogers848871b2013-08-05 10:56:33 -07001538 DCHECK(obj != NULL);
1539 DCHECK(class_linker != NULL);
1540
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001541 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001542 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001543 if (!method->IsNative()) {
1544 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
1545 if (method != Runtime::Current()->GetResolutionMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001546 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1547 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers848871b2013-08-05 10:56:33 -07001548 }
1549 }
1550 }
1551}
1552
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001553void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001554 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001555 CHECK(!init_done_);
1556
Mathieu Chartier590fee92013-09-13 13:46:47 -07001557 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001558 gc::Heap* heap = Runtime::Current()->GetHeap();
1559 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001560 dex_cache_image_class_lookup_required_ = true;
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001561 CHECK(space != NULL);
1562 OatFile& oat_file = GetImageOatFile(space);
1563 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1564 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001565 const char* image_file_location = oat_file.GetOatHeader().
1566 GetStoreValueByKey(OatHeader::kImageLocationKey);
1567 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001568 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1569 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001570 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1571 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001572 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001573 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001574 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1575 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1576 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001577
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001578 StackHandleScope<1> hs(self);
1579 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1580 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1581 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001582 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001583
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001584 // Special case of setting up the String class early so that we can test arbitrary objects
1585 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001586 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001587
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001588 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001589 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001590 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001591 StackHandleScope<1> hs(self);
1592 Handle<mirror::DexCache> dex_cache(hs.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001593 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001594 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1595 nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001596 CHECK(oat_dex_file != NULL) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001597 std::string error_msg;
1598 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001599 if (dex_file == NULL) {
1600 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001601 << " from within oat file " << oat_file.GetLocation()
1602 << " error '" << error_msg << "'";
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001603 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001604
1605 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1606
1607 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001608 }
1609
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001610 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1611 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001612 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001613
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001614 // Set entry point to interpreter if in InterpretOnly mode.
1615 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001616 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001617 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001618 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001619
1620 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001621 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001622 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001623
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001624 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001625 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
1626 DCHECK(array_iftable_.Read() == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001627 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001628 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001629 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001630 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1631 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1632 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1633 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1634 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1635 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1636 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1637 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1638 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1639 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001640
Ian Rogers98379392014-02-24 16:53:16 -08001641 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001642
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001643 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001644}
1645
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001646void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1647 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1648 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001649 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1650 it.second.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001651 }
1652 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1653 for (auto& pair : new_class_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001654 mirror::Class* old_ref = pair.second.Read<kWithoutReadBarrier>();
1655 pair.second.VisitRoot(callback, arg, 0, kRootStickyClass);
1656 mirror::Class* new_ref = pair.second.Read<kWithoutReadBarrier>();
1657 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001658 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1659 // corresponding object. This is slow, but luckily for us, this may only happen with a
1660 // concurrent moving GC.
1661 for (auto it = class_table_.lower_bound(pair.first), end = class_table_.end();
1662 it != end && it->first == pair.first; ++it) {
1663 // If the class stored matches the old class, update it to the new value.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001664 if (old_ref == it->second.Read<kWithoutReadBarrier>()) {
1665 it->second = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001666 }
1667 }
1668 }
1669 }
1670 }
1671 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1672 new_class_roots_.clear();
1673 }
1674 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1675 log_new_class_table_roots_ = true;
1676 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1677 log_new_class_table_roots_ = false;
1678 }
1679 // We deliberately ignore the class roots in the image since we
1680 // handle image roots by using the MS/CMS rescanning of dirty cards.
1681}
1682
Brian Carlstroma663ea52011-08-19 23:33:41 -07001683// Keep in sync with InitCallback. Anything we visit, we need to
1684// reinit references to when reinitializing a ClassLinker from a
1685// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001686void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001687 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001688 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001689 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001690 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001691 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001692 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1693 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001694 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001695 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1696 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001697 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001698 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001699 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001700 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1701 new_dex_cache_roots_.clear();
1702 }
1703 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1704 log_new_dex_caches_roots_ = true;
1705 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1706 log_new_dex_caches_roots_ = false;
1707 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001708 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001709 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001710 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1711 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001712 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001713 if (!find_array_class_cache_[i].IsNull()) {
1714 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001715 }
1716 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001717}
1718
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001719void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1720 if (dex_cache_image_class_lookup_required_) {
1721 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001722 }
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001723 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001724 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1725 mirror::Class* c = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07001726 if (!visitor(c, arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001727 return;
1728 }
1729 }
1730}
1731
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001732static bool GetClassesVisitor(mirror::Class* c, void* arg) {
1733 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001734 classes->insert(c);
1735 return true;
1736}
1737
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001738void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001739 std::set<mirror::Class*> classes;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001740 VisitClasses(GetClassesVisitor, &classes);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001741 for (mirror::Class* klass : classes) {
1742 if (!visitor(klass, arg)) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001743 return;
1744 }
1745 }
1746}
1747
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001748ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001749 mirror::Class::ResetClass();
1750 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001751 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001752 mirror::ArtField::ResetClass();
1753 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001754 mirror::BooleanArray::ResetArrayClass();
1755 mirror::ByteArray::ResetArrayClass();
1756 mirror::CharArray::ResetArrayClass();
1757 mirror::DoubleArray::ResetArrayClass();
1758 mirror::FloatArray::ResetArrayClass();
1759 mirror::IntArray::ResetArrayClass();
1760 mirror::LongArray::ResetArrayClass();
1761 mirror::ShortArray::ResetArrayClass();
1762 mirror::Throwable::ResetClass();
1763 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001764 STLDeleteElements(&boot_class_path_);
1765 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001766}
1767
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001768mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001769 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001770 StackHandleScope<16> hs(self);
1771 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1772 Handle<mirror::DexCache> dex_cache(
1773 hs.NewHandle(down_cast<mirror::DexCache*>(
1774 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1775 VoidFunctor()))));
1776 if (dex_cache.Get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001777 return NULL;
1778 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001779 Handle<mirror::String>
1780 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
1781 if (location.Get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001782 return NULL;
1783 }
Ian Rogers700a4022014-05-19 16:49:03 -07001784 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001785 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
1786 if (strings.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001787 return NULL;
1788 }
Ian Rogers700a4022014-05-19 16:49:03 -07001789 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001790 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
1791 if (types.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001792 return NULL;
1793 }
Ian Rogers700a4022014-05-19 16:49:03 -07001794 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001795 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
1796 if (methods.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001797 return NULL;
1798 }
Ian Rogers700a4022014-05-19 16:49:03 -07001799 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001800 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
1801 if (fields.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001802 return NULL;
1803 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001804 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1805 fields.Get());
1806 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001807}
1808
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001809mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001810 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001811 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001812 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001813 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001814 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001815 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1816 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001817 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001818 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001819 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001820 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001821 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001822}
1823
Ian Rogers6fac4472014-02-25 17:01:10 -08001824mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001825 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001826}
1827
Brian Carlstromea46f952013-07-30 01:26:50 -07001828mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001829 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001830 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001831}
1832
Brian Carlstromea46f952013-07-30 01:26:50 -07001833mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001834 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001835 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001836}
1837
Mathieu Chartier590fee92013-09-13 13:46:47 -07001838mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1839 Thread* self, size_t length) {
1840 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1841 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001842}
1843
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001844mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1845 mirror::Class* klass) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001846 DCHECK(klass != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001847
1848 // For temporary classes we must wait for them to be retired.
1849 if (init_done_ && klass->IsTemp()) {
1850 CHECK(!klass->IsResolved());
1851 if (klass->IsErroneous()) {
1852 ThrowEarlierClassFailure(klass);
1853 return nullptr;
1854 }
1855 StackHandleScope<1> hs(self);
1856 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1857 ObjectLock<mirror::Class> lock(self, h_class);
1858 // Loop and wait for the resolving thread to retire this class.
1859 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1860 lock.WaitIgnoringInterrupts();
1861 }
1862 if (h_class->IsErroneous()) {
1863 ThrowEarlierClassFailure(h_class.Get());
1864 return nullptr;
1865 }
1866 CHECK(h_class->IsRetired());
1867 // Get the updated class from class table.
1868 klass = LookupClass(descriptor, h_class.Get()->GetClassLoader());
1869 }
1870
Brian Carlstromaded5f72011-10-07 17:15:04 -07001871 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001872 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001873 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001874 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
1875 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001876 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001877 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
1878 ThrowClassCircularityError(h_class.Get());
1879 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001880 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001881 }
1882 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001883 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08001884 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001885 }
1886 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001887
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001888 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001889 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001890 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001891 }
1892 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001893 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08001894 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001895 return klass;
1896}
1897
Ian Rogers98379392014-02-24 16:53:16 -08001898mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07001899 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001900 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08001901 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001902 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001903 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001904 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1905 // for primitive classes that aren't backed by dex files.
1906 return FindPrimitiveClass(descriptor[0]);
1907 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001908 // Find the class in the loaded classes table.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001909 mirror::Class* klass = LookupClass(descriptor, class_loader.Get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001910 if (klass != NULL) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001911 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001912 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001913 // Class is not yet loaded.
1914 if (descriptor[0] == '[') {
Ian Rogers98379392014-02-24 16:53:16 -08001915 return CreateArrayClass(self, descriptor, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001916 } else if (class_loader.Get() == nullptr) {
Jesse Wilson47daf872011-11-23 11:42:45 -05001917 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1918 if (pair.second != NULL) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001919 StackHandleScope<1> hs(self);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07001920 return DefineClass(descriptor, NullHandle<mirror::ClassLoader>(), *pair.first, *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05001921 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001922 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogersbe7149f2013-08-20 09:29:39 -07001923 // First try the boot class path, we check the descriptor first to avoid an unnecessary
1924 // throw of a NoClassDefFoundError.
1925 if (IsInBootClassPath(descriptor)) {
Ian Rogers98379392014-02-24 16:53:16 -08001926 mirror::Class* system_class = FindSystemClass(self, descriptor);
Ian Rogersbe7149f2013-08-20 09:29:39 -07001927 CHECK(system_class != NULL);
Jesse Wilson47daf872011-11-23 11:42:45 -05001928 return system_class;
1929 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07001930 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001931 const std::vector<const DexFile*>* class_path;
1932 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07001933 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001934 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001935 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001936 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
1937 }
1938
1939 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, *class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001940 if (pair.second != NULL) {
1941 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001942 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001943
1944 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001945 ScopedObjectAccessUnchecked soa(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001946 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001947 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08001948 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001949 ScopedLocalRef<jobject> result(soa.Env(), NULL);
Ian Rogers365c1022012-06-22 15:05:28 -07001950 {
1951 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001952 ScopedLocalRef<jobject> class_name_object(soa.Env(),
1953 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers365c1022012-06-22 15:05:28 -07001954 if (class_name_object.get() == NULL) {
1955 return NULL;
1956 }
1957 CHECK(class_loader_object.get() != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001958 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
1959 WellKnownClasses::java_lang_ClassLoader_loadClass,
1960 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05001961 }
Ian Rogers98379392014-02-24 16:53:16 -08001962 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001963 // If the ClassLoader threw, pass that exception up.
1964 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001965 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001966 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers62d6c772013-02-27 08:32:07 -08001967 ThrowNullPointerException(NULL, StringPrintf("ClassLoader.loadClass returned null for %s",
1968 class_name_string.c_str()).c_str());
Ian Rogerscab01012012-01-10 17:35:46 -08001969 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001970 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001971 // success, return mirror::Class*
1972 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001973 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001974 }
1975
Elliott Hughes82914b62012-04-09 15:56:29 -07001976 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001977 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001978}
1979
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001980mirror::Class* ClassLinker::DefineClass(const char* descriptor,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07001981 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001982 const DexFile& dex_file,
1983 const DexFile::ClassDef& dex_class_def) {
Ian Rogers1f539342012-10-03 21:09:42 -07001984 Thread* self = Thread::Current();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001985 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001986 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001987 bool should_allocate = false;
1988
Brian Carlstromaded5f72011-10-07 17:15:04 -07001989 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001990 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001991 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001992 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001993 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001994 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001995 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001996 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001997 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07001998 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
1999 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002000 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002001 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002002 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002003 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002004 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002005 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002006 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002007 should_allocate = true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002008 }
2009 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002010 should_allocate = true;
2011 }
2012
2013 if (should_allocate) {
2014 // Allocate a class with the status of not ready.
2015 // Interface object should get the right size here. Regular class will
2016 // figure out the right size later and be replaced with one of the right
2017 // size when the class becomes resolved.
2018 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002019 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002020 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002021 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002022 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002023 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002024 klass->SetDexCache(FindDexCache(dex_file));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002025 LoadClass(dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002026 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002027 if (self->IsExceptionPending()) {
2028 // An exception occured during load, set status to erroneous while holding klass' lock in case
2029 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002030 if (!klass->IsErroneous()) {
2031 klass->SetStatus(mirror::Class::kStatusError, self);
2032 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002033 return nullptr;
2034 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002035 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002036
Mathieu Chartier590fee92013-09-13 13:46:47 -07002037 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002038 mirror::Class* existing = InsertClass(descriptor, klass.Get(), Hash(descriptor));
Ian Rogersc114b5f2014-07-21 08:55:01 -07002039 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002040 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2041 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002042 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002043 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002044
Brian Carlstromaded5f72011-10-07 17:15:04 -07002045 // Finish loading (if necessary) by finding parents
2046 CHECK(!klass->IsLoaded());
2047 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2048 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002049 if (!klass->IsErroneous()) {
2050 klass->SetStatus(mirror::Class::kStatusError, self);
2051 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002052 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002053 }
2054 CHECK(klass->IsLoaded());
2055 // Link the class (if necessary)
2056 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002057 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002058 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002059
2060 mirror::Class* new_class = nullptr;
2061 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002062 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002063 if (!klass->IsErroneous()) {
2064 klass->SetStatus(mirror::Class::kStatusError, self);
2065 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002066 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002067 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002068 CHECK(new_class != nullptr) << descriptor;
2069 CHECK(new_class->IsResolved()) << descriptor;
2070
2071 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002072
2073 /*
2074 * We send CLASS_PREPARE events to the debugger from here. The
2075 * definition of "preparation" is creating the static fields for a
2076 * class and initializing them to the standard default values, but not
2077 * executing any code (that comes later, during "initialization").
2078 *
2079 * We did the static preparation in LinkClass.
2080 *
2081 * The class has been prepared and resolved but possibly not yet verified
2082 * at this point.
2083 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002084 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002085
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002086 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002087}
2088
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002089uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2090 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002091 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002092 size_t num_ref = 0;
2093 size_t num_32 = 0;
2094 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002095 if (class_data != NULL) {
2096 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2097 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002098 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002099 char c = descriptor[0];
2100 if (c == 'L' || c == '[') {
2101 num_ref++;
2102 } else if (c == 'J' || c == 'D') {
2103 num_64++;
2104 } else {
2105 num_32++;
2106 }
2107 }
2108 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002109 return mirror::Class::ComputeClassSize(false, 0, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002110}
2111
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002112bool ClassLinker::FindOatClass(const DexFile& dex_file,
2113 uint16_t class_def_idx,
2114 OatFile::OatClass* oat_class) {
2115 DCHECK(oat_class != nullptr);
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002116 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Ian Rogers19846512012-02-24 11:42:47 -08002117 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002118 if (oat_file == nullptr) {
2119 return false;
2120 }
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07002121 uint dex_location_checksum = dex_file.GetLocationChecksum();
Ian Rogers8d31bbd2013-10-13 10:44:14 -07002122 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation().c_str(),
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07002123 &dex_location_checksum);
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002124 CHECK(oat_dex_file != NULL) << dex_file.GetLocation();
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002125 *oat_class = oat_dex_file->GetOatClass(class_def_idx);
2126 return true;
Ian Rogers19846512012-02-24 11:42:47 -08002127}
2128
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002129static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2130 uint32_t method_idx) {
2131 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
2132 const byte* class_data = dex_file.GetClassData(class_def);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002133 CHECK(class_data != NULL);
2134 ClassDataItemIterator it(dex_file, class_data);
2135 // Skip fields
2136 while (it.HasNextStaticField()) {
2137 it.Next();
2138 }
2139 while (it.HasNextInstanceField()) {
2140 it.Next();
2141 }
2142 // Process methods
2143 size_t class_def_method_index = 0;
2144 while (it.HasNextDirectMethod()) {
2145 if (it.GetMemberIndex() == method_idx) {
2146 return class_def_method_index;
2147 }
2148 class_def_method_index++;
2149 it.Next();
2150 }
2151 while (it.HasNextVirtualMethod()) {
2152 if (it.GetMemberIndex() == method_idx) {
2153 return class_def_method_index;
2154 }
2155 class_def_method_index++;
2156 it.Next();
2157 }
2158 DCHECK(!it.HasNext());
2159 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2160 return 0;
2161}
2162
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002163bool ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, OatFile::OatMethod* oat_method) {
2164 DCHECK(oat_method != nullptr);
Ian Rogers19846512012-02-24 11:42:47 -08002165 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002166 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002167 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002168 size_t oat_method_index;
2169 if (method->IsStatic() || method->IsDirect()) {
2170 // Simple case where the oat method index was stashed at load time.
2171 oat_method_index = method->GetMethodIndex();
2172 } else {
2173 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2174 // by search for its position in the declared virtual methods.
2175 oat_method_index = declaring_class->NumDirectMethods();
2176 size_t end = declaring_class->NumVirtualMethods();
2177 bool found = false;
2178 for (size_t i = 0; i < end; i++) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08002179 if (declaring_class->GetVirtualMethod(i) == method) {
2180 found = true;
2181 break;
2182 }
Ian Rogersf320b632012-03-13 18:47:47 -07002183 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002184 }
2185 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method);
2186 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002187 DCHECK_EQ(oat_method_index,
2188 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002189 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002190 method->GetDexMethodIndex()));
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002191 OatFile::OatClass oat_class;
2192 if (!FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2193 declaring_class->GetDexClassDefIndex(),
2194 &oat_class)) {
2195 return false;
2196 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002197
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002198 *oat_method = oat_class.GetOatMethod(oat_method_index);
2199 return true;
TDYa12785321912012-04-01 15:24:56 -07002200}
2201
2202// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002203const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002204 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002205 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002206 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002207 }
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002208 OatFile::OatMethod oat_method;
2209 const void* result = nullptr;
2210 if (FindOatMethodFor(method, &oat_method)) {
2211 result = oat_method.GetQuickCode();
2212 }
2213
Ian Rogersef7d42f2014-01-06 12:55:46 -08002214 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002215 if (method->IsNative()) {
2216 // No code and native? Use generic trampoline.
2217 result = GetQuickGenericJniTrampoline();
2218 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002219 // No code? Do we expect portable code?
2220 result = GetQuickToPortableBridge();
2221 } else {
2222 // No code? You must mean to go into the interpreter.
2223 result = GetQuickToInterpreterBridge();
2224 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002225 }
2226 return result;
TDYa12785321912012-04-01 15:24:56 -07002227}
2228
Ian Rogersef7d42f2014-01-06 12:55:46 -08002229const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2230 bool* have_portable_code) {
2231 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2232 *have_portable_code = false;
2233 if (method->IsProxyMethod()) {
2234 return GetPortableProxyInvokeHandler();
2235 }
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002236 OatFile::OatMethod oat_method;
2237 const void* result = nullptr;
2238 const void* quick_code = nullptr;
2239 if (FindOatMethodFor(method, &oat_method)) {
2240 result = oat_method.GetPortableCode();
2241 quick_code = oat_method.GetQuickCode();
2242 }
2243
Ian Rogersef7d42f2014-01-06 12:55:46 -08002244 if (result == nullptr) {
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002245 if (quick_code == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002246 // No code? You must mean to go into the interpreter.
2247 result = GetPortableToInterpreterBridge();
2248 } else {
2249 // No code? But there's quick code, so use a bridge.
2250 result = GetPortableToQuickBridge();
2251 }
2252 } else {
2253 *have_portable_code = true;
2254 }
2255 return result;
2256}
2257
2258const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2259 uint32_t method_idx) {
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002260 OatFile::OatClass oat_class;
2261 if (!FindOatClass(dex_file, class_def_idx, &oat_class)) {
2262 return nullptr;
2263 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002264 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002265 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002266}
2267
2268const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2269 uint32_t method_idx) {
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002270 OatFile::OatClass oat_class;
2271 if (!FindOatClass(dex_file, class_def_idx, &oat_class)) {
2272 return nullptr;
2273 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002274 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002275 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002276}
2277
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002278// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002279static bool NeedsInterpreter(
2280 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2281 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002282 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002283 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002284 // May return true for native code, in the case of generic JNI
2285 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002286 return true;
2287 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002288#ifdef ART_SEA_IR_MODE
2289 ScopedObjectAccess soa(Thread::Current());
2290 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2291 LOG(INFO) << "Found " << PrettyMethod(method);
2292 return false;
2293 }
2294#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002295 // If interpreter mode is enabled, every method (except native and proxy) must
2296 // be run with interpreter.
2297 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2298 !method->IsNative() && !method->IsProxyMethod();
2299}
2300
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002301void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002302 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002303 if (klass->NumDirectMethods() == 0) {
2304 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002305 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002306 Runtime* runtime = Runtime::Current();
2307 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light507e6182014-08-19 14:23:13 -07002308 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2309 return; // OAT file unavailable.
2310 }
Ian Rogers19846512012-02-24 11:42:47 -08002311 }
Alex Light507e6182014-08-19 14:23:13 -07002312
Mathieu Chartierf8322842014-05-16 10:59:25 -07002313 const DexFile& dex_file = klass->GetDexFile();
2314 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002315 CHECK(dex_class_def != nullptr);
2316 const byte* class_data = dex_file.GetClassData(*dex_class_def);
2317 // There should always be class data if there were direct methods.
2318 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002319 ClassDataItemIterator it(dex_file, class_data);
2320 // Skip fields
2321 while (it.HasNextStaticField()) {
2322 it.Next();
2323 }
2324 while (it.HasNextInstanceField()) {
2325 it.Next();
2326 }
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002327 OatFile::OatClass oat_class;
2328 bool has_oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(), &oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002329 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002330 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002331 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002332 if (!method->IsStatic()) {
2333 // Only update static methods.
2334 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002335 }
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002336 const void* portable_code = nullptr;
2337 const void* quick_code = nullptr;
2338 if (has_oat_class) {
2339 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2340 portable_code = oat_method.GetPortableCode();
2341 quick_code = oat_method.GetQuickCode();
2342 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002343 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2344 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002345 if (enter_interpreter) {
2346 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002347 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002348 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
2349 quick_code = GetQuickGenericJniTrampoline();
Ian Rogers1a570662014-03-12 01:02:21 -07002350 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002351 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002352 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002353 quick_code = GetQuickToInterpreterBridge();
2354 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002355 } else {
2356 if (portable_code == nullptr) {
2357 portable_code = GetPortableToQuickBridge();
2358 } else {
2359 have_portable_code = true;
2360 }
2361 if (quick_code == nullptr) {
2362 quick_code = GetQuickToPortableBridge();
2363 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002364 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002365 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2366 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002367 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002368 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002369}
2370
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002371void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method, const OatFile::OatClass* oat_class,
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002372 const DexFile& dex_file, uint32_t dex_method_index,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002373 uint32_t method_index) {
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002374 if (Runtime::Current()->IsCompiler()) {
2375 // The following code only applies to a non-compiler runtime.
2376 return;
2377 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002378 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002379 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2380 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002381 if (oat_class != nullptr) {
2382 // Every kind of method should at least get an invoke stub from the oat_method.
2383 // non-abstract methods also get their code pointers.
2384 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
2385 oat_method.LinkMethod(method.Get());
2386 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002387
Jeff Hao16743632013-05-08 10:59:04 -07002388 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002389 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002390 method->GetEntryPointFromQuickCompiledCode(),
2391 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002392 if (enter_interpreter && !method->IsNative()) {
Ian Rogers848871b2013-08-05 10:56:33 -07002393 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002394 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002395 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002396 }
2397
Brian Carlstrom92827a52011-10-10 15:50:01 -07002398 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002399 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2400 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002401 return;
2402 }
Ian Rogers19846512012-02-24 11:42:47 -08002403
Ian Rogersef7d42f2014-01-06 12:55:46 -08002404 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002405 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002406 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002407 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2408 // after initializing class (see ClassLinker::InitializeClass method).
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002409 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionTrampoline());
2410 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionTrampoline());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002411 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002412 if (!method->IsNative()) {
2413 // Set entry point from compiled code if there's no code or in interpreter only mode.
2414 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2415 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2416 } else {
2417 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniTrampoline());
2418 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2419 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002420 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2421 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2422 have_portable_code = true;
2423 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2424 } else {
2425 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2426 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002427 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002428
Ian Rogers62d6c772013-02-27 08:32:07 -08002429 if (method->IsNative()) {
2430 // Unregistering restores the dlsym lookup stub.
2431 method->UnregisterNative(Thread::Current());
Andreas Gampe90546832014-03-12 18:07:19 -07002432
2433 if (enter_interpreter) {
2434 // We have a native method here without code. Then it should have either the GenericJni
2435 // trampoline as entrypoint (non-static), or the Resolution trampoline (static).
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002436 DCHECK(method->GetEntryPointFromQuickCompiledCode() == GetQuickResolutionTrampoline()
Andreas Gampe9a6a99a2014-03-14 07:52:20 -07002437 || method->GetEntryPointFromQuickCompiledCode() == GetQuickGenericJniTrampoline());
Andreas Gampe90546832014-03-12 18:07:19 -07002438 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002439 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002440
Ian Rogers62d6c772013-02-27 08:32:07 -08002441 // Allow instrumentation its chance to hijack code.
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002442 Runtime* runtime = Runtime::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002443 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002444 method->GetEntryPointFromQuickCompiledCode(),
2445 method->GetEntryPointFromPortableCompiledCode(),
2446 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002447}
2448
Brian Carlstromf615a612011-07-23 12:50:34 -07002449void ClassLinker::LoadClass(const DexFile& dex_file,
2450 const DexFile::ClassDef& dex_class_def,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002451 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002452 mirror::ClassLoader* class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002453 CHECK(klass.Get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002454 CHECK(klass->GetDexCache() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002455 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002456 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002457 CHECK(descriptor != NULL);
2458
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002459 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002460 if (kUseBakerOrBrooksReadBarrier) {
2461 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002462 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002463 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07002464 // Make sure that none of our runtime-only flags are set.
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002465 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002466 klass->SetAccessFlags(access_flags);
2467 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002468 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002469 klass->SetStatus(mirror::Class::kStatusIdx, NULL);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002470
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002471 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002472 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002473
Ian Rogers0571d352011-11-03 19:51:38 -07002474 const byte* class_data = dex_file.GetClassData(dex_class_def);
2475 if (class_data == NULL) {
2476 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002477 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002478
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002479 OatFile::OatClass oat_class;
2480 if (Runtime::Current()->IsStarted()
2481 && !Runtime::Current()->UseCompileTimeClassPath()
2482 && FindOatClass(dex_file, klass->GetDexClassDefIndex(), &oat_class)) {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002483 LoadClassMembers(dex_file, class_data, klass, class_loader, &oat_class);
2484 } else {
2485 LoadClassMembers(dex_file, class_data, klass, class_loader, nullptr);
2486 }
2487}
2488
2489void ClassLinker::LoadClassMembers(const DexFile& dex_file,
2490 const byte* class_data,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002491 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002492 mirror::ClassLoader* class_loader,
2493 const OatFile::OatClass* oat_class) {
2494 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002495 ClassDataItemIterator it(dex_file, class_data);
Ian Rogers50b35e22012-10-04 10:09:15 -07002496 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07002497 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002498 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
2499 if (UNLIKELY(statics == NULL)) {
2500 CHECK(self->IsExceptionPending()); // OOME.
2501 return;
2502 }
2503 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002504 }
2505 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002506 mirror::ObjectArray<mirror::ArtField>* fields =
2507 AllocArtFieldArray(self, it.NumInstanceFields());
2508 if (UNLIKELY(fields == NULL)) {
2509 CHECK(self->IsExceptionPending()); // OOME.
2510 return;
2511 }
2512 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002513 }
2514 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002515 StackHandleScope<1> hs(self);
2516 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
2517 if (UNLIKELY(sfield.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002518 CHECK(self->IsExceptionPending()); // OOME.
2519 return;
2520 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002521 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002522 LoadField(dex_file, it, klass, sfield);
2523 }
2524 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002525 StackHandleScope<1> hs(self);
2526 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
2527 if (UNLIKELY(ifield.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002528 CHECK(self->IsExceptionPending()); // OOME.
2529 return;
2530 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002531 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002532 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002533 }
2534
Ian Rogers0571d352011-11-03 19:51:38 -07002535 // Load methods.
2536 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002537 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002538 mirror::ObjectArray<mirror::ArtMethod>* directs =
2539 AllocArtMethodArray(self, it.NumDirectMethods());
2540 if (UNLIKELY(directs == NULL)) {
2541 CHECK(self->IsExceptionPending()); // OOME.
2542 return;
2543 }
2544 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002545 }
Ian Rogers0571d352011-11-03 19:51:38 -07002546 if (it.NumVirtualMethods() != 0) {
2547 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002548 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2549 AllocArtMethodArray(self, it.NumVirtualMethods());
2550 if (UNLIKELY(virtuals == NULL)) {
2551 CHECK(self->IsExceptionPending()); // OOME.
2552 return;
2553 }
2554 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002555 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002556 size_t class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002557 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002558 StackHandleScope<1> hs(self);
2559 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
2560 if (UNLIKELY(method.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002561 CHECK(self->IsExceptionPending()); // OOME.
2562 return;
2563 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002564 klass->SetDirectMethod(i, method.Get());
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002565 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002566 method->SetMethodIndex(class_def_method_index);
2567 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002568 }
2569 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002570 StackHandleScope<1> hs(self);
2571 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
2572 if (UNLIKELY(method.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002573 CHECK(self->IsExceptionPending()); // OOME.
2574 return;
2575 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002576 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002577 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002578 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002579 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002580 }
2581 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002582}
2583
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002584void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002585 Handle<mirror::Class> klass, Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002586 uint32_t field_idx = it.GetMemberIndex();
2587 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002588 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002589 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002590}
2591
Brian Carlstromea46f952013-07-30 01:26:50 -07002592mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002593 const ClassDataItemIterator& it,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002594 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002595 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002596 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002597 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002598
Brian Carlstromea46f952013-07-30 01:26:50 -07002599 mirror::ArtMethod* dst = AllocArtMethod(self);
Ian Rogersa436fde2013-08-27 23:34:06 -07002600 if (UNLIKELY(dst == NULL)) {
2601 CHECK(self->IsExceptionPending()); // OOME.
2602 return NULL;
2603 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002604 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002605
Ian Rogers50b35e22012-10-04 10:09:15 -07002606 const char* old_cause = self->StartAssertNoThreadSuspension("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002607 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002608 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002609 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002610
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002611 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
Ian Rogers19846512012-02-24 11:42:47 -08002612 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002613 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002614
Ian Rogers241b5de2013-10-09 17:58:57 -07002615 uint32_t access_flags = it.GetMemberAccessFlags();
2616
Ian Rogersdfb325e2013-10-30 01:00:44 -07002617 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002618 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002619 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2620 // Void return type.
Ian Rogerscb6b0f32014-08-12 02:30:58 -07002621 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002622 klass->SetFinalizable();
2623 } else {
Ian Rogerscb6b0f32014-08-12 02:30:58 -07002624 std::string temp;
2625 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002626 // The Enum class declares a "final" finalize() method to prevent subclasses from
2627 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2628 // subclasses, so we exclude it here.
2629 // We also want to avoid setting the flag on Object, where we know that finalize() is
2630 // empty.
Ian Rogerscb6b0f32014-08-12 02:30:58 -07002631 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2632 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002633 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002634 }
2635 }
2636 }
2637 } else if (method_name[0] == '<') {
2638 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002639 bool is_init = (strcmp("<init>", method_name) == 0);
2640 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002641 if (UNLIKELY(!is_init && !is_clinit)) {
2642 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2643 } else {
2644 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2645 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002646 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002647 access_flags |= kAccConstructor;
2648 }
2649 }
2650 }
2651 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002652
Ian Rogers50b35e22012-10-04 10:09:15 -07002653 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002654 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002655}
2656
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002657void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002658 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002659 StackHandleScope<1> hs(self);
2660 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
2661 CHECK(dex_cache.Get() != NULL) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002662 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002663}
2664
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002665void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002666 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002667 CHECK(dex_cache.Get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002668 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002669 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002670}
2671
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002672bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002673 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002674 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002675 mirror::DexCache* dex_cache = GetDexCache(i);
2676 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002677 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002678 }
2679 }
2680 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002681}
2682
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002683bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002684 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002685 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002686}
2687
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002688void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002689 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002690 dex_lock_.AssertExclusiveHeld(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002691 CHECK(dex_cache.Get() != NULL) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002692 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2693 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002694 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002695 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002696 if (log_new_dex_caches_roots_) {
2697 // TODO: This is not safe if we can remove dex caches.
2698 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2699 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002700}
2701
Brian Carlstromaded5f72011-10-07 17:15:04 -07002702void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002703 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002704 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002705 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002706 if (IsDexFileRegisteredLocked(dex_file)) {
2707 return;
2708 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002709 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002710 // Don't alloc while holding the lock, since allocation may need to
2711 // suspend all threads and another thread may need the dex_lock_ to
2712 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002713 StackHandleScope<1> hs(self);
2714 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
2715 CHECK(dex_cache.Get() != NULL) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002716 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002717 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002718 if (IsDexFileRegisteredLocked(dex_file)) {
2719 return;
2720 }
2721 RegisterDexFileLocked(dex_file, dex_cache);
2722 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002723}
2724
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002725void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002726 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002727 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002728 RegisterDexFileLocked(dex_file, dex_cache);
2729}
2730
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002731mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002732 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002733 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002734 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002735 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002736 if (dex_cache->GetDexFile() == &dex_file) {
2737 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002738 }
2739 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002740 // Search matching by location name.
2741 std::string location(dex_file.GetLocation());
2742 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002743 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002744 if (dex_cache->GetDexFile()->GetLocation() == location) {
2745 return dex_cache;
2746 }
2747 }
2748 // Failure, dump diagnostic and abort.
2749 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002750 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002751 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
2752 }
2753 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002754 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002755}
2756
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002757void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002758 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08002759 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002760 mirror::DexCache* dex_cache = GetDexCache(i);
2761 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08002762 }
2763}
2764
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002765mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002766 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Ian Rogersa436fde2013-08-27 23:34:06 -07002767 if (UNLIKELY(klass == NULL)) {
2768 return NULL;
2769 }
2770 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002771}
2772
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002773mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
2774 Primitive::Type type) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002775 CHECK(primitive_class != NULL);
Ian Rogers1f539342012-10-03 21:09:42 -07002776 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002777 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002778 StackHandleScope<1> hs(self);
2779 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002780 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002781 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002782 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002783 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
2784 const char* descriptor = Primitive::Descriptor(type);
2785 mirror::Class* existing = InsertClass(descriptor, primitive_class, Hash(descriptor));
Ian Rogersc8982582012-09-07 16:53:25 -07002786 CHECK(existing == NULL) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002787 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07002788}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002789
Brian Carlstrombe977852011-07-19 14:54:54 -07002790// Create an array class (i.e. the class object for the array, not the
2791// array itself). "descriptor" looks like "[C" or "[[[[B" or
2792// "[Ljava/lang/String;".
2793//
2794// If "descriptor" refers to an array of primitives, look up the
2795// primitive type's internally-generated class object.
2796//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002797// "class_loader" is the class loader of the class that's referring to
2798// us. It's used to ensure that we're looking for the element type in
2799// the right context. It does NOT become the class loader for the
2800// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07002801//
2802// Returns NULL with an exception raised on failure.
Ian Rogers98379392014-02-24 16:53:16 -08002803mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002804 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002805 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002806 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002807 StackHandleScope<2> hs(self);
2808 Handle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1, class_loader)));
2809 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002810 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002811 // We need to accept erroneous classes as component types.
2812 component_type.Assign(LookupClass(descriptor + 1, class_loader.Get()));
2813 if (component_type.Get() == nullptr) {
2814 DCHECK(self->IsExceptionPending());
2815 return nullptr;
2816 } else {
2817 self->ClearException();
2818 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002819 }
Ian Rogers2d10b202014-05-12 19:15:18 -07002820 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
2821 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
2822 return nullptr;
2823 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002824 // See if the component type is already loaded. Array classes are
2825 // always associated with the class loader of their underlying
2826 // element type -- an array of Strings goes with the loader for
2827 // java/lang/String -- so we need to look for it there. (The
2828 // caller should have checked for the existence of the class
2829 // before calling here, but they did so with *their* class loader,
2830 // not the component type's loader.)
2831 //
2832 // If we find it, the caller adds "loader" to the class' initiating
2833 // loader list, which should prevent us from going through this again.
2834 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002835 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002836 // are the same, because our caller (FindClass) just did the
2837 // lookup. (Even if we get this wrong we still have correct behavior,
2838 // because we effectively do this lookup again when we add the new
2839 // class to the hash table --- necessary because of possible races with
2840 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002841 if (class_loader.Get() != component_type->GetClassLoader()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002842 mirror::Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002843 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002844 return new_class;
2845 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002846 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002847
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002848 // Fill out the fields in the Class.
2849 //
2850 // It is possible to execute some methods against arrays, because
2851 // all arrays are subclasses of java_lang_Object_, so we need to set
2852 // up a vtable. We can just point at the one in java_lang_Object_.
2853 //
2854 // Array classes are simple enough that we don't need to do a full
2855 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002856 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002857 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002858 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002859 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002860 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002861 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002862 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002863 } else if (strcmp(descriptor, class_roots_descriptors_[kJavaLangStringArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002864 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002865 } else if (strcmp(descriptor,
2866 class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002867 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002868 } else if (strcmp(descriptor,
2869 class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002870 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002871 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002872 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002873 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002874 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002875 }
2876 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002877 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002878 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002879 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002880 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002881 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002882 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002883 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002884 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002885 DCHECK(new_class->GetComponentType() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002886 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002887 new_class->SetSuperClass(java_lang_Object);
2888 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002889 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002890 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002891 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
2892 new_class->PopulateEmbeddedImtAndVTable();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002893 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002894 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002895 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002896
2897
2898 // All arrays have java/lang/Cloneable and java/io/Serializable as
2899 // interfaces. We need to set that up here, so that stuff like
2900 // "instanceof" works right.
2901 //
2902 // Note: The GC could run during the call to FindSystemClass,
2903 // so we need to make sure the class object is GC-valid while we're in
2904 // there. Do this by clearing the interface list so the GC will just
2905 // think that the entries are null.
2906
2907
2908 // Use the single, global copies of "interfaces" and "iftable"
2909 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002910 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002911 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002912 CHECK(array_iftable != nullptr);
2913 new_class->SetIfTable(array_iftable);
2914 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002915
Elliott Hughes00626c22013-06-14 15:04:14 -07002916 // Inherit access flags from the component type.
2917 int access_flags = new_class->GetComponentType()->GetAccessFlags();
2918 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2919 access_flags &= kAccJavaFlagsMask;
2920 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002921 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07002922 access_flags |= kAccAbstract | kAccFinal;
2923 access_flags &= ~kAccInterface;
2924
2925 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002926
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002927 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), Hash(descriptor));
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002928 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002929 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002930 }
2931 // Another thread must have loaded the class after we
2932 // started but before we finished. Abandon what we've
2933 // done.
2934 //
2935 // (Yes, this happens.)
2936
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002937 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002938}
2939
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002940mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07002941 switch (type) {
2942 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002943 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07002944 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002945 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07002946 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002947 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07002948 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002949 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07002950 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002951 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07002952 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002953 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07002954 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002955 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07002956 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002957 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07002958 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002959 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07002960 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002961 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07002962 }
Elliott Hughesbd935992011-08-22 11:59:34 -07002963 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002964 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07002965 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002966}
2967
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002968mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
2969 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002970 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002971 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08002972 std::string source;
2973 if (dex_cache != NULL) {
2974 source += " from ";
2975 source += dex_cache->GetLocation()->ToModifiedUtf8();
2976 }
2977 LOG(INFO) << "Loaded class " << descriptor << source;
2978 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002979 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07002980 mirror::Class* existing =
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002981 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002982 if (existing != NULL) {
2983 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07002984 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002985 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == NULL &&
2986 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002987 // Check a class loaded with the system class loader matches one in the image if the class
2988 // is in the image.
2989 existing = LookupClassFromImage(descriptor);
2990 if (existing != NULL) {
2991 CHECK(klass == existing);
2992 }
2993 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08002994 VerifyObject(klass);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002995 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002996 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002997 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002998 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002999 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003000}
3001
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003002mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3003 size_t hash) {
3004 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3005 mirror::Class* existing =
3006 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
3007
3008 if (existing == nullptr) {
3009 CHECK(klass->IsProxyClass());
3010 return nullptr;
3011 }
3012
3013 CHECK_NE(existing, klass) << descriptor;
3014 CHECK(!existing->IsResolved()) << descriptor;
3015 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3016
3017 for (auto it = class_table_.lower_bound(hash), end = class_table_.end(); it != end && it->first == hash;
3018 ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003019 mirror::Class* klass = it->second.Read();
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07003020 if (klass == existing) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003021 class_table_.erase(it);
3022 break;
3023 }
3024 }
3025
3026 CHECK(!klass->IsTemp()) << descriptor;
3027 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3028 dex_cache_image_class_lookup_required_) {
3029 // Check a class loaded with the system class loader matches one in the image if the class
3030 // is in the image.
3031 existing = LookupClassFromImage(descriptor);
3032 if (existing != nullptr) {
3033 CHECK(klass == existing) << descriptor;
3034 }
3035 }
3036 VerifyObject(klass);
3037
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003038 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003039 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003040 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003041 }
3042
3043 return existing;
3044}
3045
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003046bool ClassLinker::RemoveClass(const char* descriptor, const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003047 size_t hash = Hash(descriptor);
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003048 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Brian Carlstromf3632832014-05-20 15:36:53 -07003049 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3050 it != end && it->first == hash;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003051 ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003052 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003053 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003054 class_table_.erase(it);
Brian Carlstromae826982011-11-09 01:33:42 -08003055 return true;
3056 }
3057 }
3058 return false;
3059}
3060
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003061mirror::Class* ClassLinker::LookupClass(const char* descriptor,
3062 const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003063 size_t hash = Hash(descriptor);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003064 {
3065 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3066 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
3067 if (result != NULL) {
3068 return result;
3069 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003070 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003071 if (class_loader != NULL || !dex_cache_image_class_lookup_required_) {
3072 return NULL;
3073 } else {
3074 // Lookup failed but need to search dex_caches_.
3075 mirror::Class* result = LookupClassFromImage(descriptor);
3076 if (result != NULL) {
3077 InsertClass(descriptor, result, hash);
3078 } else {
3079 // Searching the image dex files/caches failed, we don't want to get into this situation
3080 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3081 // classes into the class table.
3082 const int32_t kMaxFailedDexCacheLookups = 1000;
3083 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3084 MoveImageClassesToClassTable();
3085 }
3086 }
3087 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003088 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003089}
3090
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003091mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
3092 const mirror::ClassLoader* class_loader,
3093 size_t hash) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003094 auto end = class_table_.end();
3095 for (auto it = class_table_.lower_bound(hash); it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003096 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003097 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003098 if (kIsDebugBuild) {
3099 // Check for duplicates in the table.
3100 for (++it; it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003101 mirror::Class* klass2 = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003102 CHECK(!(klass2->GetClassLoader() == class_loader &&
3103 klass2->DescriptorEquals(descriptor)))
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003104 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
3105 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003106 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003107 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003108 return klass;
3109 }
3110 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003111 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003112}
3113
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003114static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3115 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3116 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
3117 CHECK(image != NULL);
3118 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3119 return root->AsObjectArray<mirror::DexCache>();
3120}
3121
3122void ClassLinker::MoveImageClassesToClassTable() {
3123 Thread* self = Thread::Current();
3124 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3125 if (!dex_cache_image_class_lookup_required_) {
3126 return; // All dex cache classes are already in the class table.
3127 }
3128 const char* old_no_suspend_cause =
3129 self->StartAssertNoThreadSuspension("Moving image classes to class table");
3130 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogerscb6b0f32014-08-12 02:30:58 -07003131 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003132 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3133 mirror::DexCache* dex_cache = dex_caches->Get(i);
3134 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3135 for (int32_t j = 0; j < types->GetLength(); j++) {
3136 mirror::Class* klass = types->Get(j);
3137 if (klass != NULL) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003138 DCHECK(klass->GetClassLoader() == NULL);
Ian Rogerscb6b0f32014-08-12 02:30:58 -07003139 const char* descriptor = klass->GetDescriptor(&temp);
3140 size_t hash = Hash(descriptor);
3141 mirror::Class* existing = LookupClassFromTableLocked(descriptor, NULL, hash);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003142 if (existing != NULL) {
3143 CHECK(existing == klass) << PrettyClassAndClassLoader(existing) << " != "
3144 << PrettyClassAndClassLoader(klass);
3145 } else {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003146 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003147 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003148 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003149 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003150 }
3151 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003152 }
3153 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003154 dex_cache_image_class_lookup_required_ = false;
3155 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3156}
3157
3158mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
3159 Thread* self = Thread::Current();
3160 const char* old_no_suspend_cause =
3161 self->StartAssertNoThreadSuspension("Image class lookup");
3162 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3163 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3164 mirror::DexCache* dex_cache = dex_caches->Get(i);
3165 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003166 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003167 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
3168 if (string_id != NULL) {
3169 const DexFile::TypeId* type_id =
3170 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
3171 if (type_id != NULL) {
3172 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3173 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
3174 if (klass != NULL) {
3175 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3176 return klass;
3177 }
3178 }
3179 }
3180 }
3181 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3182 return NULL;
3183}
3184
3185void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3186 result.clear();
3187 if (dex_cache_image_class_lookup_required_) {
3188 MoveImageClassesToClassTable();
3189 }
3190 size_t hash = Hash(descriptor);
3191 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003192 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
Mathieu Chartier02e25112013-08-14 16:14:24 -07003193 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003194 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003195 if (klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003196 result.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003197 }
3198 }
3199}
3200
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003201void ClassLinker::VerifyClass(Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003202 // TODO: assert that the monitor on the Class is held
Ian Rogers1f539342012-10-03 21:09:42 -07003203 Thread* self = Thread::Current();
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003204 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003205
Ian Rogers9ffb0392012-09-10 11:56:50 -07003206 // Don't attempt to re-verify if already sufficiently verified.
3207 if (klass->IsVerified() ||
3208 (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler())) {
jeffhao98eacac2011-09-14 16:11:53 -07003209 return;
3210 }
3211
Ian Rogers9ffb0392012-09-10 11:56:50 -07003212 // The class might already be erroneous, for example at compile time if we attempted to verify
3213 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003214 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003215 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003216 return;
3217 }
3218
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003219 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003220 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003221 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003222 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003223 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003224 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003225 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003226 }
jeffhao98eacac2011-09-14 16:11:53 -07003227
Jeff Hao4a200f52014-04-01 14:58:49 -07003228 // Skip verification if disabled.
3229 if (!Runtime::Current()->IsVerificationEnabled()) {
3230 klass->SetStatus(mirror::Class::kStatusVerified, self);
3231 return;
3232 }
3233
Ian Rogers9ffb0392012-09-10 11:56:50 -07003234 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003235 StackHandleScope<2> hs(self);
3236 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
3237 if (super.Get() != NULL) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003238 // Acquire lock to prevent races on verifying the super class.
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003239 ObjectLock<mirror::Class> lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003240
3241 if (!super->IsVerified() && !super->IsErroneous()) {
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003242 VerifyClass(super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003243 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003244 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003245 std::string error_msg(
3246 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3247 PrettyDescriptor(klass.Get()).c_str(),
3248 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003249 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003250 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3251 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003252 self->ClearException();
3253 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003254 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3255 if (cause.Get() != nullptr) {
3256 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003257 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003258 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003259 if (Runtime::Current()->IsCompiler()) {
3260 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3261 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003262 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003263 return;
3264 }
3265 }
3266
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003267 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003268 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003269 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003270 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003271 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003272 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003273 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003274 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003275 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3276 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003277 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003278 return;
3279 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003280 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003281 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003282 if (!preverified) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003283 verifier_failure = verifier::MethodVerifier::VerifyClass(klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003284 Runtime::Current()->IsCompiler(),
3285 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003286 }
3287 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003288 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003289 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003290 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3291 << " because: " << error_msg;
3292 }
Ian Rogers1f539342012-10-03 21:09:42 -07003293 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003294 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003295 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003296 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003297 // Even though there were no verifier failures we need to respect whether the super-class
3298 // was verified or requiring runtime reverification.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003299 if (super.Get() == NULL || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003300 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003301 } else {
3302 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003303 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003304 // Pretend a soft failure occured so that we don't consider the class verified below.
3305 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003306 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003307 } else {
3308 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3309 // Soft failures at compile time should be retried at runtime. Soft
3310 // failures at runtime will be handled by slow paths in the generated
3311 // code. Set status accordingly.
3312 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003313 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003314 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003315 klass->SetStatus(mirror::Class::kStatusVerified, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003316 }
3317 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003318 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003319 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003320 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3321 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003322 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003323 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003324 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003325 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003326 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003327 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003328 // Let the interpreter know it by setting the kAccPreverified flag onto each
3329 // method.
3330 // Note: we're going here during compilation and at runtime. When we set the
3331 // kAccPreverified flag when compiling image classes, the flag is recorded
3332 // in the image and is set when loading the image.
3333 klass->SetPreverifiedFlagOnAllMethods();
3334 }
jeffhao98eacac2011-09-14 16:11:53 -07003335}
3336
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003337bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3338 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003339 // If we're compiling, we can only verify the class using the oat file if
3340 // we are not compiling the image or if the class we're verifying is not part of
3341 // the app. In other words, we will only check for preverification of bootclasspath
3342 // classes.
3343 if (Runtime::Current()->IsCompiler()) {
3344 // Are we compiling the bootclasspath?
3345 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3346 return false;
3347 }
3348 // We are compiling an app (not the image).
3349
3350 // Is this an app class? (I.e. not a bootclasspath class)
3351 if (klass->GetClassLoader() != NULL) {
3352 return false;
3353 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003354 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003355
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003356 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003357 // Make this work with gtests, which do not set up the image properly.
3358 // TODO: we should clean up gtests to set up the image path properly.
Nicolas Geoffray9c290012014-07-22 10:48:00 +01003359 if (Runtime::Current()->IsCompiler() || (oat_file == NULL)) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003360 return false;
3361 }
3362
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003363 CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07003364 uint dex_location_checksum = dex_file.GetLocationChecksum();
Ian Rogers8d31bbd2013-10-13 10:44:14 -07003365 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation().c_str(),
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07003366 &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003367 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003368 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003369 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003370 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3371 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003372 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003373 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003374 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003375 // Compile time verification failed with a soft error. Compile time verification can fail
3376 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003377 // class ... {
3378 // Foo x;
3379 // .... () {
3380 // if (...) {
3381 // v1 gets assigned a type of resolved class Foo
3382 // } else {
3383 // v1 gets assigned a type of unresolved class Bar
3384 // }
3385 // iput x = v1
3386 // } }
3387 // when we merge v1 following the if-the-else it results in Conflict
3388 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3389 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3390 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3391 // at compile time).
3392 return false;
3393 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003394 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003395 // Compile time verification failed with a hard error. This is caused by invalid instructions
3396 // in the class. These errors are unrecoverable.
3397 return false;
3398 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003399 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003400 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3401 // not loading the class.
3402 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3403 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003404 return false;
3405 }
Ian Rogerscb6b0f32014-08-12 02:30:58 -07003406 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003407 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003408 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogerscb6b0f32014-08-12 02:30:58 -07003409 << klass->GetDescriptor(&temp);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003410
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003411 return false;
3412}
3413
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003414void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003415 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003416 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3417 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3418 }
3419 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3420 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3421 }
3422}
3423
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003424void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003425 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003426 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3427 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
3428 if (code_item == NULL) {
3429 return; // native or abstract method
3430 }
3431 if (code_item->tries_size_ == 0) {
3432 return; // nothing to process
3433 }
3434 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
3435 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3436 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3437 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3438 CatchHandlerIterator iterator(handlers_ptr);
3439 for (; iterator.HasNext(); iterator.Next()) {
3440 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3441 // unresolved exception types will be ignored by exception delivery
3442 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003443 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003444 if (exception_type == NULL) {
3445 DCHECK(Thread::Current()->IsExceptionPending());
3446 Thread::Current()->ClearException();
3447 }
3448 }
3449 }
3450 handlers_ptr = iterator.EndDataPointer();
3451 }
3452}
3453
Brian Carlstromea46f952013-07-30 01:26:50 -07003454static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003455static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003456 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003457
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003458mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003459 jobjectArray interfaces, jobject loader,
3460 jobjectArray methods, jobjectArray throws) {
3461 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003462 StackHandleScope<8> hs(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003463 Handle<mirror::Class> klass(hs.NewHandle(
3464 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003465 if (klass.Get() == NULL) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003466 CHECK(self->IsExceptionPending()); // OOME.
3467 return NULL;
3468 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003469 DCHECK(klass->GetClass() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003470 klass->SetObjectSize(sizeof(mirror::Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003471 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003472 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003473 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003474 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003475 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003476 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003477 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003478
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003479 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003480 {
3481 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
3482 if (UNLIKELY(sfields == NULL)) {
3483 CHECK(self->IsExceptionPending()); // OOME.
3484 return NULL;
3485 }
3486 klass->SetSFields(sfields);
3487 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003488 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3489 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003490 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3491 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003492 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003493 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003494 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003495 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003496 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003497 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003498 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3499 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003500 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3501 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003502 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003503 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003504 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003505 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003506 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003507 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003508 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003509
Ian Rogers466bb252011-10-14 03:29:56 -07003510 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003511 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003512 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003513 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003514 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003515 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003516 }
3517 klass->SetDirectMethods(directs);
3518 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003519 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003520 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003521 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003522 }
3523 klass->SetDirectMethod(0, constructor);
3524 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003525
Mathieu Chartier590fee92013-09-13 13:46:47 -07003526 // Create virtual method using specified prototypes.
3527 size_t num_virtual_methods =
3528 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003529 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003530 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3531 num_virtual_methods);
Ian Rogersa436fde2013-08-27 23:34:06 -07003532 if (UNLIKELY(virtuals == NULL)) {
3533 CHECK(self->IsExceptionPending()); // OOME.
3534 return NULL;
3535 }
3536 klass->SetVirtualMethods(virtuals);
3537 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003538 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003539 StackHandleScope<1> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003540 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3541 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003542 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003543 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003544 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003545 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003546 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003547 }
3548 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003549 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003550
3551 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003552 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003553 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003554
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003555 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3556 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003557 {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003558 ObjectLock<mirror::Class> resolution_lock(self, klass); // Must hold lock on object when resolved.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003559 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003560 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003561 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003562 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003563 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003564 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003565 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003566 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003567
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003568 CHECK(klass->IsRetired());
3569 CHECK_NE(klass.Get(), new_class);
3570 klass.Assign(new_class);
3571
3572 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
3573 interfaces_sfield->SetObject<false>(klass.Get(), soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
3574 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
3575 throws_sfield->SetObject<false>(klass.Get(), soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
3576
3577 {
3578 // Lock on klass is released. Lock new class object.
3579 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003580 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003581 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003582
3583 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003584 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003585 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003586 CheckProxyConstructor(klass->GetDirectMethod(0));
3587 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003588 StackHandleScope<2> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003589 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3590 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003591 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003592 Handle<mirror::ArtMethod> virtual_method(hs.NewHandle(klass->GetVirtualMethod(i)));
3593 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003594 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003595
Mathieu Chartier590fee92013-09-13 13:46:47 -07003596 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003597 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003598 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003599 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3600
3601 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003602 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003603 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003604
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003605 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003606 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003607 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003608 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003609 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003610 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003611 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003612 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003613}
3614
Ian Rogersef7d42f2014-01-06 12:55:46 -08003615std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003616 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003617 mirror::String* name = proxy_class->GetName();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003618 DCHECK(name != NULL);
3619 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3620}
3621
Ian Rogersef7d42f2014-01-06 12:55:46 -08003622mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3623 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003624 DCHECK(proxy_class->IsProxyClass());
3625 DCHECK(proxy_method->IsProxyMethod());
3626 // Locate the dex cache of the original interface/Object
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003627 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003628 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003629 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003630 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003631 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003632 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003633 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003634 break;
3635 }
3636 }
3637 }
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003638 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003639 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003640 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003641 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003642 return resolved_method;
3643}
3644
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003645
Brian Carlstromea46f952013-07-30 01:26:50 -07003646mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003647 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003648 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003649 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003650 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003651 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003652 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3653 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertz440d3da2014-08-27 15:32:56 +02003654 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3655 // constructor method.
3656 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3657 proxy_constructor);
Jeff Hao95b4c652014-08-14 17:18:52 -07003658 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3659 // code_ too)
Jeff Hao4bf8d112014-07-24 16:26:09 -07003660 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3661 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003662 CHECK(self->IsExceptionPending()); // OOME.
Jeff Hao4bf8d112014-07-24 16:26:09 -07003663 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003664 }
Ian Rogers466bb252011-10-14 03:29:56 -07003665 // Make this constructor public and fix the class to be our Proxy version
3666 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003667 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003668 return constructor;
3669}
3670
Brian Carlstromea46f952013-07-30 01:26:50 -07003671static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003672 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003673 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003674 CHECK_STREQ(constructor->GetName(), "<init>");
3675 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3676 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003677 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003678}
3679
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003680mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003681 Handle<mirror::Class> klass,
3682 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003683 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3684 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08003685 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003686 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003687 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003688 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003689 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Ian Rogersa436fde2013-08-27 23:34:06 -07003690 if (UNLIKELY(method == NULL)) {
3691 CHECK(self->IsExceptionPending()); // OOME.
3692 return NULL;
3693 }
Ian Rogers466bb252011-10-14 03:29:56 -07003694
3695 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3696 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003697 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07003698 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003699
Ian Rogers466bb252011-10-14 03:29:56 -07003700 // At runtime the method looks like a reference and argument saving method, clone the code
3701 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003702 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
3703 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07003704 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08003705
Ian Rogersc2b44472011-12-14 21:17:17 -08003706 return method;
3707}
Jesse Wilson95caa792011-10-12 18:14:17 -04003708
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003709static void CheckProxyMethod(Handle<mirror::ArtMethod> method, Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003710 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003711 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003712 CHECK(!prototype->IsFinal());
3713 CHECK(method->IsFinal());
3714 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08003715
3716 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
3717 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
3718 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003719 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
3720 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08003721 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
3722
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003723 MethodHelper mh(method);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003724 MethodHelper mh2(prototype);
3725 CHECK_STREQ(method->GetName(), prototype->GetName());
3726 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07003727 // More complex sanity - via dex cache
Ian Rogers19846512012-02-24 11:42:47 -08003728 CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04003729}
3730
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003731static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
3732 bool can_init_parents)
3733 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003734 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003735 return true;
3736 }
3737 if (!can_init_statics) {
3738 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07003739 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003740 if (clinit != NULL) {
3741 return false;
3742 }
3743 // Check if there are encoded static values needing initialization.
3744 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003745 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003746 DCHECK(dex_class_def != NULL);
3747 if (dex_class_def->static_values_off_ != 0) {
3748 return false;
3749 }
3750 }
3751 }
3752 if (!klass->IsInterface() && klass->HasSuperClass()) {
3753 mirror::Class* super_class = klass->GetSuperClass();
3754 if (!can_init_parents && !super_class->IsInitialized()) {
3755 return false;
3756 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003757 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003758 return false;
3759 }
3760 }
3761 }
3762 return true;
3763}
3764
Mathieu Chartier590fee92013-09-13 13:46:47 -07003765bool ClassLinker::IsInitialized() const {
3766 return init_done_;
3767}
3768
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003769bool ClassLinker::InitializeClass(Handle<mirror::Class> klass, bool can_init_statics,
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003770 bool can_init_parents) {
3771 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
3772
3773 // Are we already initialized and therefore done?
3774 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
3775 // an initialized class will never change its state.
3776 if (klass->IsInitialized()) {
3777 return true;
3778 }
3779
3780 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003781 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003782 return false;
3783 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003784
Carl Shapirob5573532011-07-12 18:22:59 -07003785 Thread* self = Thread::Current();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003786 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003787 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003788 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003789
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003790 // Re-check under the lock in case another thread initialized ahead of us.
3791 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003792 return true;
3793 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003794
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003795 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003796 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003797 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromd1422f82011-09-28 11:37:09 -07003798 return false;
3799 }
3800
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003801 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003802
3803 if (!klass->IsVerified()) {
jeffhao98eacac2011-09-14 16:11:53 -07003804 VerifyClass(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003805 if (!klass->IsVerified()) {
3806 // We failed to verify, expect either the klass to be erroneous or verification failed at
3807 // compile time.
3808 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07003809 CHECK(self->IsExceptionPending());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003810 } else {
3811 CHECK(Runtime::Current()->IsCompiler());
3812 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07003813 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003814 return false;
3815 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003816 }
3817
Brian Carlstromd1422f82011-09-28 11:37:09 -07003818 // If the class is kStatusInitializing, either this thread is
3819 // initializing higher up the stack or another thread has beat us
3820 // to initializing and we need to wait. Either way, this
3821 // invocation of InitializeClass will not be responsible for
3822 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003823 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07003824 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07003825 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003826 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003827 return true;
3828 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003829 // No. That's fine. Wait for another thread to finish initializing.
3830 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003831 }
3832
3833 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003834 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003835 return false;
3836 }
3837
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003838 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003839
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003840 // From here out other threads may observe that we're initializing and so changes of state
3841 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07003842 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003843 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003844
3845 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003846 }
3847
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003848 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003849 if (!klass->IsInterface() && klass->HasSuperClass()) {
3850 mirror::Class* super_class = klass->GetSuperClass();
3851 if (!super_class->IsInitialized()) {
3852 CHECK(!super_class->IsInterface());
3853 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003854 StackHandleScope<1> hs(self);
3855 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
3856 bool super_initialized = InitializeClass(handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003857 if (!super_initialized) {
3858 // The super class was verified ahead of entering initializing, we should only be here if
3859 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003860 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07003861 << "Super class initialization failed for "
3862 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003863 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003864 << "\nPending exception:\n"
3865 << (self->GetException(NULL) != NULL ? self->GetException(NULL)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003866 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003867 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003868 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003869 return false;
3870 }
Ian Rogers1bddec32012-02-04 12:27:34 -08003871 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003872 }
3873
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003874 if (klass->NumStaticFields() > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003875 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003876 CHECK(dex_class_def != NULL);
Mathieu Chartierf8322842014-05-16 10:59:25 -07003877 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003878 StackHandleScope<2> hs(self);
3879 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07003880 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07003881 EncodedStaticFieldValueIterator it(dex_file, &dex_cache, &class_loader,
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003882 this, *dex_class_def);
3883 if (it.HasNext()) {
3884 CHECK(can_init_statics);
Brian Carlstromf3632832014-05-20 15:36:53 -07003885 // We reordered the fields, so we need to be able to map the
3886 // field indexes to the right fields.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003887 SafeMap<uint32_t, mirror::ArtField*> field_map;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003888 ConstructFieldMap(dex_file, *dex_class_def, klass.Get(), field_map);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003889 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003890 if (Runtime::Current()->IsActiveTransaction()) {
3891 it.ReadValueToField<true>(field_map.Get(i));
3892 } else {
3893 it.ReadValueToField<false>(field_map.Get(i));
3894 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003895 }
3896 }
3897 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003898
Ian Rogersd91d6d62013-09-25 20:26:14 -07003899 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003900 if (clinit != NULL) {
3901 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07003902 JValue result;
3903 clinit->Invoke(self, NULL, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003904 }
3905
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003906 uint64_t t1 = NanoTime();
3907
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003908 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003909 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003910 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003911
3912 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07003913 WrapExceptionInInitializer();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003914 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003915 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003916 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003917 RuntimeStats* global_stats = Runtime::Current()->GetStats();
3918 RuntimeStats* thread_stats = self->GetStats();
3919 ++global_stats->class_init_count;
3920 ++thread_stats->class_init_count;
3921 global_stats->class_init_time_ns += (t1 - t0);
3922 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003923 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003924 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003925 if (VLOG_IS_ON(class_linker)) {
Ian Rogerscb6b0f32014-08-12 02:30:58 -07003926 std::string temp;
3927 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07003928 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08003929 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08003930 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003931 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003932 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003933 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003934 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003935}
3936
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003937bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003938 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003939 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003940 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003941 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003942 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08003943 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003944
3945 // When we wake up, repeat the test for init-in-progress. If
3946 // there's an exception pending (only possible if
3947 // "interruptShouldThrow" was set), bail out.
3948 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07003949 WrapExceptionInInitializer();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003950 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003951 return false;
3952 }
3953 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003954 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003955 continue;
3956 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003957 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07003958 // Compile time initialization failed.
3959 return false;
3960 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003961 if (klass->IsErroneous()) {
3962 // The caller wants an exception, but it was thrown in a
3963 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07003964 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003965 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07003966 return false;
3967 }
3968 if (klass->IsInitialized()) {
3969 return true;
3970 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003971 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003972 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003973 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003974 LOG(FATAL) << "Not Reached" << PrettyClass(klass.Get());
Brian Carlstromd1422f82011-09-28 11:37:09 -07003975}
3976
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003977bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003978 if (klass->IsInterface()) {
3979 return true;
3980 }
Ian Rogers151f2212014-05-06 11:27:27 -07003981 // Begin with the methods local to the superclass.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003982 StackHandleScope<2> hs(Thread::Current());
3983 MethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
3984 MethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003985 if (klass->HasSuperClass() &&
3986 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07003987 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
3988 mh.ChangeMethod(klass->GetVTableEntry(i));
3989 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003990 if (mh.GetMethod() != super_mh.GetMethod() &&
3991 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
3992 ThrowLinkageError(klass.Get(),
3993 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003994 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07003995 PrettyMethod(mh.GetMethod()).c_str(),
3996 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003997 return false;
3998 }
3999 }
4000 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004001 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004002 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4003 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4004 for (uint32_t j = 0; j < num_methods; ++j) {
4005 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4006 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004007 if (mh.GetMethod() != super_mh.GetMethod() &&
4008 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
4009 ThrowLinkageError(klass.Get(),
4010 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004011 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004012 PrettyMethod(mh.GetMethod()).c_str(),
4013 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004014 return false;
4015 }
4016 }
4017 }
4018 }
4019 return true;
4020}
4021
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004022bool ClassLinker::EnsureInitialized(Handle<mirror::Class> c, bool can_init_fields,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004023 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004024 DCHECK(c.Get() != nullptr);
4025 const bool success = c->IsInitialized() || InitializeClass(c, can_init_fields, can_init_parents);
4026 if (!success && can_init_fields && can_init_parents) {
4027 CHECK(Thread::Current()->IsExceptionPending()) << PrettyClass(c.Get());
Ian Rogers595799e2012-01-11 17:32:51 -08004028 }
4029 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004030}
4031
Elliott Hughes5fe594f2011-09-08 12:33:17 -07004032void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Mathieu Chartier590fee92013-09-13 13:46:47 -07004033 mirror::Class* c,
4034 SafeMap<uint32_t, mirror::ArtField*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07004035 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07004036 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004037 StackHandleScope<2> hs(Thread::Current());
4038 Handle<mirror::DexCache> dex_cache(hs.NewHandle(c->GetDexCache()));
4039 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(c->GetClassLoader()));
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004040 CHECK(!kMovingFields);
Ian Rogers0571d352011-11-03 19:51:38 -07004041 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004042 field_map.Put(i, ResolveField(dex_file, it.GetMemberIndex(), dex_cache, class_loader, true));
Elliott Hughes5fe594f2011-09-08 12:33:17 -07004043 }
4044}
4045
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004046void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4047 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4048 if (fields != nullptr) {
4049 for (int index = 0; index < fields->GetLength(); index ++) {
4050 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4051 fields->Get(index)->SetDeclaringClass(new_class);
4052 }
4053 }
4054 }
4055
4056 fields = new_class->GetSFields();
4057 if (fields != nullptr) {
4058 for (int index = 0; index < fields->GetLength(); index ++) {
4059 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4060 fields->Get(index)->SetDeclaringClass(new_class);
4061 }
4062 }
4063 }
4064
4065 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4066 if (methods != nullptr) {
4067 for (int index = 0; index < methods->GetLength(); index ++) {
4068 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4069 methods->Get(index)->SetDeclaringClass(new_class);
4070 }
4071 }
4072 }
4073
4074 methods = new_class->GetVirtualMethods();
4075 if (methods != nullptr) {
4076 for (int index = 0; index < methods->GetLength(); index ++) {
4077 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4078 methods->Get(index)->SetDeclaringClass(new_class);
4079 }
4080 }
4081 }
4082}
4083
4084bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4085 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4086 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004087 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004088
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004089 if (!LinkSuperClass(klass)) {
4090 return false;
4091 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004092 if (!LinkMethods(self, klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004093 return false;
4094 }
4095 if (!LinkInstanceFields(klass)) {
4096 return false;
4097 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004098 size_t class_size;
4099 if (!LinkStaticFields(klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004100 return false;
4101 }
4102 CreateReferenceInstanceOffsets(klass);
4103 CreateReferenceStaticOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004104 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004105
4106 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4107 // We don't need to retire this class as it has no embedded tables or it was created the
4108 // correct size during class linker initialization.
4109 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4110
4111 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
4112 klass->PopulateEmbeddedImtAndVTable();
4113 }
4114
4115 // This will notify waiters on klass that saw the not yet resolved
4116 // class in the class_table_ during EnsureResolved.
4117 klass->SetStatus(mirror::Class::kStatusResolved, self);
4118 *new_class = klass.Get();
4119 } else {
4120 CHECK(!klass->IsResolved());
4121 // Retire the temporary class and create the correctly sized resolved class.
4122 *new_class = klass->CopyOf(self, class_size);
4123 if (UNLIKELY(*new_class == NULL)) {
4124 CHECK(self->IsExceptionPending()); // Expect an OOME.
4125 klass->SetStatus(mirror::Class::kStatusError, self);
4126 return false;
4127 }
4128
4129 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4130 StackHandleScope<1> hs(self);
4131 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4132 ObjectLock<mirror::Class> lock(self, new_class_h);
4133
4134 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4135
4136 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(), Hash(descriptor));
4137 CHECK(existing == NULL || existing == klass.Get());
4138
4139 // This will notify waiters on temp class that saw the not yet resolved class in the
4140 // class_table_ during EnsureResolved.
4141 klass->SetStatus(mirror::Class::kStatusRetired, self);
4142
4143 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4144 // This will notify waiters on new_class that saw the not yet resolved
4145 // class in the class_table_ during EnsureResolved.
4146 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004147 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004148 return true;
4149}
4150
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004151bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004152 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004153 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4154 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004155 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004156 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004157 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004158 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004159 return false;
4160 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004161 // Verify
4162 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004163 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004164 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004165 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004166 return false;
4167 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004168 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004169 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004170 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004171 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004172 if (interfaces != NULL) {
4173 for (size_t i = 0; i < interfaces->Size(); i++) {
4174 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004175 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004176 if (interface == NULL) {
4177 DCHECK(Thread::Current()->IsExceptionPending());
4178 return false;
4179 }
4180 // Verify
4181 if (!klass->CanAccess(interface)) {
4182 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004183 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004184 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004185 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004186 return false;
4187 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004188 }
4189 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004190 // Mark the class as loaded.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004191 klass->SetStatus(mirror::Class::kStatusLoaded, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004192 return true;
4193}
4194
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004195bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004196 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004197 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004198 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004199 if (super != NULL) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004200 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004201 return false;
4202 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004203 return true;
4204 }
4205 if (super == NULL) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004206 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4207 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004208 return false;
4209 }
4210 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004211 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004212 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004213 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004214 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004215 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004216 return false;
4217 }
4218 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004219 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004220 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004221 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004222 return false;
4223 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004224
Brian Carlstromf3632832014-05-20 15:36:53 -07004225 // Inherit kAccClassIsFinalizable from the superclass in case this
4226 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004227 if (super->IsFinalizable()) {
4228 klass->SetFinalizable();
4229 }
4230
Elliott Hughes2da50362011-10-10 16:57:08 -07004231 // Inherit reference flags (if any) from the superclass.
4232 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4233 if (reference_flags != 0) {
4234 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4235 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004236 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004237 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004238 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004239 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004240 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004241 return false;
4242 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004243
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004244 if (kIsDebugBuild) {
4245 // Ensure super classes are fully resolved prior to resolving fields..
4246 while (super != NULL) {
4247 CHECK(super->IsResolved());
4248 super = super->GetSuperClass();
4249 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004250 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004251 return true;
4252}
4253
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004254// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004255bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004256 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004257 if (klass->IsInterface()) {
4258 // No vtable.
4259 size_t count = klass->NumVirtualMethods();
4260 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004261 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004262 return false;
4263 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004264 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004265 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004266 }
jeffhaobdb76512011-09-07 11:43:16 -07004267 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004268 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004269 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07004270 // Link virtual and interface method tables
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004271 return LinkVirtualMethods(self, klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004272 }
4273 return true;
4274}
4275
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004276bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004277 if (klass->HasSuperClass()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004278 uint32_t max_count = klass->NumVirtualMethods() +
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004279 klass->GetSuperClass()->GetVTableLength();
4280 size_t actual_count = klass->GetSuperClass()->GetVTableLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004281 CHECK_LE(actual_count, max_count);
Mingyao Yang82546342014-08-13 14:51:03 -07004282 StackHandleScope<4> hs(self);
4283 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004284 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004285 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4286 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4287 if (UNLIKELY(vtable.Get() == nullptr)) {
4288 CHECK(self->IsExceptionPending()); // OOME.
4289 return false;
4290 }
4291 int len = super_class->GetVTableLength();
Mingyao Yang1a128582014-07-22 17:33:25 -07004292 for (int i = 0; i < len; i++) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004293 vtable->Set<false>(i, super_class->GetVTableEntry(i));
4294 }
4295 } else {
Mingyao Yang82546342014-08-13 14:51:03 -07004296 CHECK(super_class->GetVTable() != nullptr) << PrettyClass(super_class.Get());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004297 vtable = hs.NewHandle(super_class->GetVTable()->CopyOf(self, max_count));
4298 if (UNLIKELY(vtable.Get() == nullptr)) {
4299 CHECK(self->IsExceptionPending()); // OOME.
4300 return false;
4301 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004302 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004303
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004304 // See if any of our virtual methods override the superclass.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004305 MethodHelper local_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4306 MethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004307 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004308 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004309 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004310 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004311 for (; j < actual_count; ++j) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004312 mirror::ArtMethod* super_method = vtable->Get(j);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004313 super_mh.ChangeMethod(super_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004314 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004315 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4316 super_method->GetAccessFlags())) {
Elliott Hughes39717372012-07-13 16:21:23 -07004317 if (super_method->IsFinal()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004318 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
Elliott Hughes39717372012-07-13 16:21:23 -07004319 PrettyMethod(local_method).c_str(),
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004320 super_method->GetDeclaringClassDescriptor());
Elliott Hughes39717372012-07-13 16:21:23 -07004321 return false;
4322 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004323 vtable->Set<false>(j, local_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004324 local_method->SetMethodIndex(j);
4325 break;
4326 } else {
4327 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method)
4328 << " would have incorrectly overridden the package-private method in "
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004329 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004330 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004331 }
4332 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004333 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004334 // Not overriding, append.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004335 vtable->Set<false>(actual_count, local_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004336 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004337 actual_count += 1;
4338 }
4339 }
4340 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004341 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004342 return false;
4343 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004344 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004345 CHECK_LE(actual_count, max_count);
4346 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004347 vtable.Assign(vtable->CopyOf(self, actual_count));
4348 if (UNLIKELY(vtable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004349 CHECK(self->IsExceptionPending()); // OOME.
4350 return false;
4351 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004352 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004353 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004354 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004355 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004356 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004357 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004358 ThrowClassFormatError(klass.Get(), "Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004359 return false;
4360 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004361 StackHandleScope<1> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004362 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004363 vtable(hs.NewHandle(AllocArtMethodArray(self, num_virtual_methods)));
4364 if (UNLIKELY(vtable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004365 CHECK(self->IsExceptionPending()); // OOME.
4366 return false;
4367 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004368 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004369 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004370 vtable->Set<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004371 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004372 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004373 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004374 }
4375 return true;
4376}
4377
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004378bool ClassLinker::LinkInterfaceMethods(Handle<mirror::Class> klass,
4379 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004380 Thread* const self = Thread::Current();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004381 Runtime* const runtime = Runtime::Current();
Jeff Hao88474b42013-10-23 16:24:40 -07004382 // Set the imt table to be all conflicts by default.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004383 klass->SetImTable(runtime->GetDefaultImt());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004384 size_t super_ifcount;
4385 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004386 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004387 } else {
4388 super_ifcount = 0;
4389 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07004390 uint32_t num_interfaces =
4391 interfaces.Get() == nullptr ? klass->NumDirectInterfaces() : interfaces->GetLength();
4392 size_t ifcount = super_ifcount + num_interfaces;
4393 for (size_t i = 0; i < num_interfaces; i++) {
4394 mirror::Class* interface =
4395 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4396 interfaces->Get(i);
4397 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004398 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004399 if (ifcount == 0) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004400 // Class implements no interfaces.
4401 DCHECK_EQ(klass->GetIfTableCount(), 0);
4402 DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004403 return true;
4404 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004405 if (ifcount == super_ifcount) {
4406 // Class implements same interfaces as parent, are any of these not marker interfaces?
4407 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004408 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Ian Rogers9bc81912012-10-11 21:43:36 -07004409 for (size_t i = 0; i < ifcount; ++i) {
4410 if (super_iftable->GetMethodArrayCount(i) > 0) {
4411 has_non_marker_interface = true;
4412 break;
4413 }
4414 }
4415 if (!has_non_marker_interface) {
4416 // Class just inherits marker interfaces from parent so recycle parent's iftable.
4417 klass->SetIfTable(super_iftable);
4418 return true;
4419 }
4420 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004421 StackHandleScope<4> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004422 Handle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
4423 if (UNLIKELY(iftable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004424 CHECK(self->IsExceptionPending()); // OOME.
4425 return false;
4426 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004427 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004428 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004429 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004430 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004431 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004432 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004433 }
4434 // Flatten the interface inheritance hierarchy.
4435 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004436 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004437 mirror::Class* interface =
Mathieu Chartierf8322842014-05-16 10:59:25 -07004438 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4439 interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004440 DCHECK(interface != NULL);
4441 if (!interface->IsInterface()) {
Ian Rogerscb6b0f32014-08-12 02:30:58 -07004442 std::string temp;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004443 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4444 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogerscb6b0f32014-08-12 02:30:58 -07004445 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004446 return false;
4447 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004448 // Check if interface is already in iftable
4449 bool duplicate = false;
4450 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004451 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004452 if (existing_interface == interface) {
4453 duplicate = true;
4454 break;
4455 }
4456 }
4457 if (!duplicate) {
4458 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004459 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004460 // Add this interface's non-duplicate super-interfaces.
4461 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004462 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004463 bool super_duplicate = false;
4464 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004465 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004466 if (existing_interface == super_interface) {
4467 super_duplicate = true;
4468 break;
4469 }
4470 }
4471 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004472 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004473 }
4474 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004475 }
4476 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004477 // Shrink iftable in case duplicates were found
4478 if (idx < ifcount) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004479 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
4480 if (UNLIKELY(iftable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004481 CHECK(self->IsExceptionPending()); // OOME.
4482 return false;
4483 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004484 ifcount = idx;
4485 } else {
4486 CHECK_EQ(idx, ifcount);
4487 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004488 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004489
4490 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004491 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004492 return true;
4493 }
Jeff Hao88474b42013-10-23 16:24:40 -07004494 // Allocate imtable
4495 bool imtable_changed = false;
Ian Rogers700a4022014-05-19 16:49:03 -07004496 Handle<mirror::ObjectArray<mirror::ArtMethod>> imtable(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004497 hs.NewHandle(AllocArtMethodArray(self, mirror::Class::kImtSize)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004498 if (UNLIKELY(imtable.Get() == NULL)) {
Jeff Hao88474b42013-10-23 16:24:40 -07004499 CHECK(self->IsExceptionPending()); // OOME.
4500 return false;
4501 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004502 MethodHelper interface_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4503 MethodHelper vtable_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Brian Carlstromea46f952013-07-30 01:26:50 -07004504 std::vector<mirror::ArtMethod*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004505 for (size_t i = 0; i < ifcount; ++i) {
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004506 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004507 if (num_methods > 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004508 StackHandleScope<2> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004509 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004510 method_array(hs.NewHandle(AllocArtMethodArray(self, num_methods)));
4511 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004512 CHECK(self->IsExceptionPending()); // OOME.
4513 return false;
4514 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004515 iftable->SetMethodArray(i, method_array.Get());
Ian Rogers700a4022014-05-19 16:49:03 -07004516 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004517 hs.NewHandle(klass->GetVTableDuringLinking()));
Ian Rogers62d6c772013-02-27 08:32:07 -08004518 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004519 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004520 interface_mh.ChangeMethod(interface_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004521 int32_t k;
4522 // For each method listed in the interface's method list, find the
4523 // matching method in our class's method list. We want to favor the
4524 // subclass over the superclass, which just requires walking
4525 // back from the end of the vtable. (This only matters if the
4526 // superclass defines a private method and this class redefines
4527 // it -- otherwise it would use the same vtable slot. In .dex files
4528 // those don't end up in the virtual method table, so it shouldn't
4529 // matter which direction we go. We walk it backward anyway.)
4530 for (k = vtable->GetLength() - 1; k >= 0; --k) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004531 mirror::ArtMethod* vtable_method = vtable->Get(k);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004532 vtable_mh.ChangeMethod(vtable_method);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004533 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Elliott Hughes68243612013-02-22 17:16:07 -08004534 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004535 ThrowIllegalAccessError(
4536 klass.Get(),
4537 "Method '%s' implementing interface method '%s' is not public",
4538 PrettyMethod(vtable_method).c_str(),
4539 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004540 return false;
4541 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004542 method_array->Set<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004543 // Place method in imt if entry is empty, place conflict otherwise.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004544 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
Jeff Hao88474b42013-10-23 16:24:40 -07004545 if (imtable->Get(imt_index) == NULL) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004546 imtable->Set<false>(imt_index, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004547 imtable_changed = true;
4548 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004549 imtable->Set<false>(imt_index, runtime->GetImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -07004550 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004551 break;
4552 }
4553 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004554 if (k < 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004555 StackHandleScope<1> hs(self);
4556 auto miranda_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004557 for (mirror::ArtMethod* mir_method : miranda_list) {
4558 vtable_mh.ChangeMethod(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004559 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004560 miranda_method.Assign(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004561 break;
4562 }
4563 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004564 if (miranda_method.Get() == NULL) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004565 // Point the interface table at a phantom slot.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004566 miranda_method.Assign(down_cast<mirror::ArtMethod*>(interface_method->Clone(self)));
4567 if (UNLIKELY(miranda_method.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004568 CHECK(self->IsExceptionPending()); // OOME.
4569 return false;
4570 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004571 // TODO: If a methods move then the miranda_list may hold stale references.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004572 miranda_list.push_back(miranda_method.Get());
Ian Rogers9bc81912012-10-11 21:43:36 -07004573 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004574 method_array->Set<false>(j, miranda_method.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004575 }
4576 }
4577 }
4578 }
Jeff Hao88474b42013-10-23 16:24:40 -07004579 if (imtable_changed) {
4580 // Fill in empty entries in interface method table with conflict.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004581 mirror::ArtMethod* imt_conflict_method = runtime->GetImtConflictMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004582 for (size_t i = 0; i < mirror::Class::kImtSize; i++) {
Jeff Hao88474b42013-10-23 16:24:40 -07004583 if (imtable->Get(i) == NULL) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004584 imtable->Set<false>(i, imt_conflict_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004585 }
4586 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004587 klass->SetImTable(imtable.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004588 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004589 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004590 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07004591 int new_method_count = old_method_count + miranda_list.size();
Ian Rogersa436fde2013-08-27 23:34:06 -07004592 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4593 if (old_method_count == 0) {
4594 virtuals = AllocArtMethodArray(self, new_method_count);
4595 } else {
4596 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4597 }
4598 if (UNLIKELY(virtuals == NULL)) {
4599 CHECK(self->IsExceptionPending()); // OOME.
4600 return false;
4601 }
4602 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004603
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004604 StackHandleScope<1> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004605 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004606 hs.NewHandle(klass->GetVTableDuringLinking()));
4607 CHECK(vtable.Get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004608 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07004609 int new_vtable_count = old_vtable_count + miranda_list.size();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004610 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
4611 if (UNLIKELY(vtable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004612 CHECK(self->IsExceptionPending()); // OOME.
4613 return false;
4614 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004615 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004616 mirror::ArtMethod* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07004617 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07004618 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4619 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4620 klass->SetVirtualMethod(old_method_count + i, method);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004621 vtable->Set<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004622 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004623 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004624 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004625 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004626
Brian Carlstromea46f952013-07-30 01:26:50 -07004627 mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking();
Elliott Hughes4681c802011-09-25 18:04:37 -07004628 for (int i = 0; i < vtable->GetLength(); ++i) {
4629 CHECK(vtable->Get(i) != NULL);
4630 }
4631
4632// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
4633
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004634 return true;
4635}
4636
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004637bool ClassLinker::LinkInstanceFields(Handle<mirror::Class> klass) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004638 CHECK(klass.Get() != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004639 return LinkFields(klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004640}
4641
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004642bool ClassLinker::LinkStaticFields(Handle<mirror::Class> klass, size_t* class_size) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004643 CHECK(klass.Get() != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004644 return LinkFields(klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004645}
4646
Brian Carlstromdbc05252011-09-09 01:59:59 -07004647struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004648 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4649 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004650 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004651 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004652 NO_THREAD_SAFETY_ANALYSIS {
Brian Carlstromdbc05252011-09-09 01:59:59 -07004653 // First come reference fields, then 64-bit, and finally 32-bit
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004654 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
4655 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08004656 if (type1 != type2) {
4657 bool is_primitive1 = type1 != Primitive::kPrimNot;
4658 bool is_primitive2 = type2 != Primitive::kPrimNot;
Brian Carlstromf3632832014-05-20 15:36:53 -07004659 bool is64bit1 = is_primitive1 && (type1 == Primitive::kPrimLong ||
4660 type1 == Primitive::kPrimDouble);
4661 bool is64bit2 = is_primitive2 && (type2 == Primitive::kPrimLong ||
4662 type2 == Primitive::kPrimDouble);
Ian Rogersef7d42f2014-01-06 12:55:46 -08004663 int order1 = !is_primitive1 ? 0 : (is64bit1 ? 1 : 2);
4664 int order2 = !is_primitive2 ? 0 : (is64bit2 ? 1 : 2);
4665 if (order1 != order2) {
4666 return order1 < order2;
4667 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07004668 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07004669 // same basic group? then sort by string.
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004670 return strcmp(field1->GetName(), field2->GetName()) < 0;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004671 }
4672};
4673
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004674bool ClassLinker::LinkFields(Handle<mirror::Class> klass, bool is_static, size_t* class_size) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004675 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004676 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004677
Brian Carlstromea46f952013-07-30 01:26:50 -07004678 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004679 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004680
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004681 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07004682 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004683 if (is_static) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004684 uint32_t base = sizeof(mirror::Class); // Static fields come after the class.
4685 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
4686 // Static fields come after the embedded tables.
4687 base = mirror::Class::ComputeClassSize(true, klass->GetVTableDuringLinking()->GetLength(),
4688 0, 0, 0);
4689 }
4690 field_offset = MemberOffset(base);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004691 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004692 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004693 if (super_class != NULL) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004694 CHECK(super_class->IsResolved())
4695 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004696 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004697 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004698 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004699
Brian Carlstromf3632832014-05-20 15:36:53 -07004700 CHECK_EQ(num_fields == 0, fields == NULL) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004701
Brian Carlstromdbc05252011-09-09 01:59:59 -07004702 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07004703 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07004704 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004705 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004706 mirror::ArtField* f = fields->Get(i);
Brian Carlstromf3632832014-05-20 15:36:53 -07004707 CHECK(f != NULL) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004708 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004709 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07004710 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
4711 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07004712
4713 // References should be at the front.
4714 size_t current_field = 0;
4715 size_t num_reference_fields = 0;
4716 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004717 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004718 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004719 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004720 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004721 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004722 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07004723 grouped_and_sorted_fields.pop_front();
4724 num_reference_fields++;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004725 fields->Set<false>(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004726 field->SetOffset(field_offset);
4727 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004728 }
4729
4730 // Now we want to pack all of the double-wide fields together. If
4731 // we're not aligned, though, we want to shuffle one 32-bit field
4732 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07004733 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07004734 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004735 mirror::ArtField* field = grouped_and_sorted_fields[i];
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004736 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstromf3632832014-05-20 15:36:53 -07004737 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004738 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07004739 continue;
4740 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004741 fields->Set<false>(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004742 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004743 // drop the consumed field
4744 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
4745 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004746 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07004747 // whether we found a 32-bit field for padding or not, we advance
4748 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004749 }
4750
4751 // Alignment is good, shuffle any double-wide fields forward, and
4752 // finish assigning field offsets to all fields.
Brian Carlstromf3632832014-05-20 15:36:53 -07004753 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()))
4754 << PrettyClass(klass.Get());
Brian Carlstromdbc05252011-09-09 01:59:59 -07004755 while (!grouped_and_sorted_fields.empty()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004756 mirror::ArtField* field = grouped_and_sorted_fields.front();
Brian Carlstromdbc05252011-09-09 01:59:59 -07004757 grouped_and_sorted_fields.pop_front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004758 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstromf3632832014-05-20 15:36:53 -07004759 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004760 fields->Set<false>(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004761 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004762 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004763 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07004764 ? sizeof(uint64_t)
4765 : sizeof(uint32_t)));
4766 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004767 }
4768
Elliott Hughesadb460d2011-10-05 17:02:34 -07004769 // 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 -07004770 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07004771 // We know there are no non-reference fields in the Reference classes, and we know
4772 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07004773 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004774 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07004775 --num_reference_fields;
4776 }
4777
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004778 if (kIsDebugBuild) {
4779 // Make sure that all reference fields appear before
4780 // non-reference fields, and all double-wide fields are aligned.
4781 bool seen_non_ref = false;
4782 for (size_t i = 0; i < num_fields; i++) {
4783 mirror::ArtField* field = fields->Get(i);
4784 if (false) { // enable to debug field layout
4785 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004786 << " class=" << PrettyClass(klass.Get())
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004787 << " field=" << PrettyField(field)
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07004788 << " offset="
4789 << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004790 }
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004791 Primitive::Type type = field->GetTypeAsPrimitiveType();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004792 bool is_primitive = type != Primitive::kPrimNot;
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004793 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004794 strcmp("referent", field->GetName()) == 0) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004795 is_primitive = true; // We lied above, so we have to expect a lie here.
4796 }
4797 if (is_primitive) {
4798 if (!seen_non_ref) {
4799 seen_non_ref = true;
Brian Carlstromf3632832014-05-20 15:36:53 -07004800 DCHECK_EQ(num_reference_fields, i) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004801 }
4802 } else {
Brian Carlstromf3632832014-05-20 15:36:53 -07004803 DCHECK(!seen_non_ref) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07004804 }
4805 }
4806 if (!seen_non_ref) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004807 DCHECK_EQ(num_fields, num_reference_fields) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004808 }
4809 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004810
4811 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004812 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004813 if (is_static) {
4814 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004815 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004816 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004817 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004818 if (!klass->IsVariableSize()) {
Ian Rogerscb6b0f32014-08-12 02:30:58 -07004819 std::string temp;
4820 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07004821 size_t previous_size = klass->GetObjectSize();
4822 if (previous_size != 0) {
4823 // Make sure that we didn't originally have an incorrect size.
Ian Rogerscb6b0f32014-08-12 02:30:58 -07004824 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07004825 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004826 klass->SetObjectSize(size);
4827 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004828 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004829 return true;
4830}
4831
4832// Set the bitmap of reference offsets, refOffsets, from the ifields
4833// list.
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004834void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004835 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004836 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004837 if (super_class != NULL) {
4838 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07004839 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004840 if (reference_offsets == CLASS_WALK_SUPER) {
4841 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004842 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004843 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004844 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004845 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004846}
4847
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004848void ClassLinker::CreateReferenceStaticOffsets(Handle<mirror::Class> klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004849 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004850}
4851
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004852void ClassLinker::CreateReferenceOffsets(Handle<mirror::Class> klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004853 uint32_t reference_offsets) {
4854 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004855 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
4856 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogersef7d42f2014-01-06 12:55:46 -08004857 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004858 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07004859 // All of the fields that contain object references are guaranteed
4860 // to be at the beginning of the fields list.
4861 for (size_t i = 0; i < num_reference_fields; ++i) {
4862 // Note that byte_offset is the offset from the beginning of
4863 // object, not the offset into instance data
Ian Rogersef7d42f2014-01-06 12:55:46 -08004864 mirror::ArtField* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004865 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004866 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
4867 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
4868 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07004869 CHECK_NE(new_bit, 0U);
4870 reference_offsets |= new_bit;
4871 } else {
4872 reference_offsets = CLASS_WALK_SUPER;
4873 break;
4874 }
4875 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004876 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004877 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004878 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004879 } else {
4880 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004881 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004882}
4883
Mathieu Chartier590fee92013-09-13 13:46:47 -07004884mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004885 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004886 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004887 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004888 if (resolved != NULL) {
4889 return resolved;
4890 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07004891 uint32_t utf16_length;
4892 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004893 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004894 dex_cache->SetResolvedString(string_idx, string);
4895 return string;
4896}
4897
Mathieu Chartier590fee92013-09-13 13:46:47 -07004898mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08004899 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004900 StackHandleScope<2> hs(Thread::Current());
4901 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
4902 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07004903 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
4904}
4905
4906mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004907 Handle<mirror::DexCache> dex_cache,
4908 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004909 DCHECK(dex_cache.Get() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004910 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004911 if (resolved == NULL) {
Ian Rogers98379392014-02-24 16:53:16 -08004912 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07004913 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08004914 resolved = FindClass(self, descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004915 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05004916 // TODO: we used to throw here if resolved's class loader was not the
4917 // boot class loader. This was to permit different classes with the
4918 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004919 dex_cache->SetResolvedType(type_idx, resolved);
4920 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08004921 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08004922 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08004923 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004924 StackHandleScope<1> hs(self);
4925 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08004926 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004927 DCHECK(resolved == NULL); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08004928 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08004929 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004930 self->GetException(NULL)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08004931 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004932 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004933 }
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07004934 DCHECK((resolved == NULL) || resolved->IsResolved() || resolved->IsErroneous())
4935 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004936 return resolved;
4937}
4938
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004939mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
4940 Handle<mirror::DexCache> dex_cache,
4941 Handle<mirror::ClassLoader> class_loader,
4942 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07004943 InvokeType type) {
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004944 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07004945 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07004946 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004947 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004948 return resolved;
4949 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004950 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004951 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004952 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004953 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07004954 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004955 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004956 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004957 // Scan using method_idx, this saves string compares but will only hit for matching dex
4958 // caches/files.
4959 switch (type) {
4960 case kDirect: // Fall-through.
4961 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004962 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004963 break;
4964 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004965 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004966 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004967 break;
4968 case kSuper: // Fall-through.
4969 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004970 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004971 break;
4972 default:
4973 LOG(FATAL) << "Unreachable - invocation type: " << type;
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004974 }
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004975 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004976 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004977 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07004978 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07004979 switch (type) {
4980 case kDirect: // Fall-through.
4981 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08004982 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07004983 break;
4984 case kInterface:
4985 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004986 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004987 break;
4988 case kSuper: // Fall-through.
4989 case kVirtual:
4990 resolved = klass->FindVirtualMethod(name, signature);
4991 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004992 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004993 }
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07004994 // If we found a method, check for incompatible class changes.
4995 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004996 // Be a good citizen and update the dex cache to speed subsequent calls.
4997 dex_cache->SetResolvedMethod(method_idx, resolved);
4998 return resolved;
4999 } else {
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005000 // If we had a method, it's an incompatible-class-change error.
5001 if (resolved != nullptr) {
5002 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5003 } else {
5004 // We failed to find the method which means either an access error, an incompatible class
5005 // change, or no such method. First try to find the method among direct and virtual methods.
5006 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5007 const Signature signature = dex_file.GetMethodSignature(method_id);
5008 switch (type) {
5009 case kDirect:
5010 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005011 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005012 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5013 // have had a resolved method before, which triggers the "true" branch above.
5014 break;
5015 case kInterface:
5016 case kVirtual:
5017 case kSuper:
5018 resolved = klass->FindDirectMethod(name, signature);
5019 break;
5020 }
5021
5022 // If we found something, check that it can be accessed by the referrer.
5023 if (resolved != nullptr && referrer.Get() != nullptr) {
5024 mirror::Class* methods_class = resolved->GetDeclaringClass();
5025 mirror::Class* referring_class = referrer->GetDeclaringClass();
5026 if (!referring_class->CanAccess(methods_class)) {
5027 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5028 resolved, type);
5029 return nullptr;
5030 } else if (!referring_class->CanAccessMember(methods_class,
5031 resolved->GetAccessFlags())) {
5032 ThrowIllegalAccessErrorMethod(referring_class, resolved);
5033 return nullptr;
5034 }
5035 }
5036
5037 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
5038 // methods and throw if we find the method there. If we find nothing, throw a
5039 // NoSuchMethodError.
5040 switch (type) {
5041 case kDirect:
5042 case kStatic:
5043 if (resolved != nullptr) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005044 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005045 } else {
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005046 resolved = klass->FindInterfaceMethod(name, signature);
5047 if (resolved != nullptr) {
5048 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5049 } else {
5050 ThrowNoSuchMethodError(type, klass, name, signature);
5051 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005052 }
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005053 break;
5054 case kInterface:
5055 if (resolved != nullptr) {
5056 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005057 } else {
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005058 resolved = klass->FindVirtualMethod(name, signature);
5059 if (resolved != nullptr) {
5060 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5061 } else {
5062 ThrowNoSuchMethodError(type, klass, name, signature);
5063 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005064 }
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005065 break;
5066 case kSuper:
Andreas Gampe9cb8d7a2014-08-25 20:55:01 -07005067 if (resolved != nullptr) {
5068 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5069 } else {
5070 ThrowNoSuchMethodError(type, klass, name, signature);
5071 }
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005072 break;
5073 case kVirtual:
5074 if (resolved != nullptr) {
5075 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5076 } else {
5077 resolved = klass->FindInterfaceMethod(name, signature);
5078 if (resolved != nullptr) {
5079 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5080 } else {
5081 ThrowNoSuchMethodError(type, klass, name, signature);
5082 }
5083 }
5084 break;
5085 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005086 }
5087 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005088 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005089 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005090}
5091
Mathieu Chartier590fee92013-09-13 13:46:47 -07005092mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005093 Handle<mirror::DexCache> dex_cache,
5094 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005095 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005096 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005097 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005098 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005099 return resolved;
5100 }
5101 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005102 Thread* const self = Thread::Current();
5103 StackHandleScope<1> hs(self);
5104 Handle<mirror::Class> klass(
5105 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005106 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005107 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005108 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005109 }
5110
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005111 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005112 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005113 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005114 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005115 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005116
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005117 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005118 const char* name = dex_file.GetFieldName(field_id);
5119 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5120 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005121 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005122 } else {
5123 resolved = klass->FindInstanceField(name, type);
5124 }
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005125 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005126 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005127 return NULL;
5128 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005129 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005130 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005131 return resolved;
5132}
5133
Brian Carlstromea46f952013-07-30 01:26:50 -07005134mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005135 uint32_t field_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005136 Handle<mirror::DexCache> dex_cache,
5137 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005138 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005139 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005140 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005141 return resolved;
5142 }
5143 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005144 Thread* self = Thread::Current();
5145 StackHandleScope<1> hs(self);
5146 Handle<mirror::Class> klass(
5147 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
5148 if (klass.Get() == NULL) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005149 DCHECK(Thread::Current()->IsExceptionPending());
5150 return NULL;
5151 }
5152
Ian Rogersdfb325e2013-10-30 01:00:44 -07005153 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5154 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005155 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005156 resolved = mirror::Class::FindField(self, klass, name, type);
Ian Rogersb067ac22011-12-13 18:05:09 -08005157 if (resolved != NULL) {
5158 dex_cache->SetResolvedField(field_idx, resolved);
5159 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005160 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005161 }
5162 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005163}
5164
Brian Carlstromea46f952013-07-30 01:26:50 -07005165const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005166 uint32_t* length) {
5167 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5168 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005169 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005170 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005171 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005172}
5173
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005174void ClassLinker::DumpAllClasses(int flags) {
5175 if (dex_cache_image_class_lookup_required_) {
5176 MoveImageClassesToClassTable();
5177 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005178 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5179 // 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 -08005180 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005181 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005182 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005183 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
5184 mirror::Class* klass = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07005185 all_classes.push_back(klass);
Ian Rogers5d76c432011-10-31 21:42:49 -07005186 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005187 }
5188
5189 for (size_t i = 0; i < all_classes.size(); ++i) {
5190 all_classes[i]->DumpClass(std::cerr, flags);
5191 }
5192}
5193
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005194void ClassLinker::DumpForSigQuit(std::ostream& os) {
5195 if (dex_cache_image_class_lookup_required_) {
5196 MoveImageClassesToClassTable();
5197 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005198 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005199 os << "Loaded classes: " << class_table_.size() << " allocated classes\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005200}
5201
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005202size_t ClassLinker::NumLoadedClasses() {
5203 if (dex_cache_image_class_lookup_required_) {
5204 MoveImageClassesToClassTable();
5205 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005206 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005207 return class_table_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005208}
5209
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005210pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005211 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005212}
5213
5214pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005215 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005216}
5217
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005218void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005219 DCHECK(!init_done_);
5220
5221 DCHECK(klass != NULL);
5222 DCHECK(klass->GetClassLoader() == NULL);
5223
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005224 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005225 DCHECK(class_roots != NULL);
5226 DCHECK(class_roots->Get(class_root) == NULL);
5227 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005228}
5229
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005230} // namespace art