blob: 6cec15433e34429de96604da6b486f8c1ca5891b [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>
Andreas Gampead00fed2014-12-10 20:51:45 -080022#include <unistd.h>
Brian Carlstromdbc05252011-09-09 01:59:59 -070023#include <deque>
Ian Rogers700a4022014-05-19 16:49:03 -070024#include <memory>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070025#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070026#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070027#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070028
Elliott Hughes1aa246d2012-12-13 09:29:36 -080029#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080030#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010031#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080032#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080033#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080034#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000035#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080036#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070037#include "dex_file-inl.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070038#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/accounting/card_table-inl.h"
40#include "gc/accounting/heap_bitmap.h"
41#include "gc/heap.h"
42#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070043#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070044#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070045#include "interpreter/interpreter.h"
Ian Rogers0571d352011-11-03 19:51:38 -070046#include "leb128.h"
Ian Rogerscb6b0f32014-08-12 02:30:58 -070047#include "method_helper-inl.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080048#include "oat.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070049#include "oat_file.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070050#include "object_lock.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070051#include "mirror/art_field-inl.h"
52#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080053#include "mirror/class.h"
54#include "mirror/class-inl.h"
55#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070056#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057#include "mirror/iftable-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080058#include "mirror/object-inl.h"
59#include "mirror/object_array-inl.h"
60#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070061#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080062#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070063#include "mirror/string-inl.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080064#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070065#include "runtime.h"
Ian Rogers7655f292013-07-29 11:07:13 -070066#include "entrypoints/entrypoint_utils.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070067#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070068#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070069#include "handle_scope-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070070#include "thread.h"
71#include "utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080072#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070073#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070074
75namespace art {
76
Ian Rogers00f7d0e2012-07-19 15:28:27 -070077static void ThrowNoClassDefFoundError(const char* fmt, ...)
78 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070079 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070080static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070081 va_list args;
82 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -080083 Thread* self = Thread::Current();
84 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
85 self->ThrowNewExceptionV(throw_location, "Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080086 va_end(args);
87}
88
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080089static void ThrowEarlierClassFailure(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -070090 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5c599942012-06-13 16:45:05 -070091 // The class failed to initialize on a previous attempt, so we want to throw
92 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
93 // failed in verification, in which case v2 5.4.1 says we need to re-throw
94 // the previous error.
Ian Rogers87e552d2012-08-31 15:54:48 -070095 if (!Runtime::Current()->IsCompiler()) { // Give info if this occurs at runtime.
96 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
97 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -070098
Elliott Hughes5c599942012-06-13 16:45:05 -070099 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800100 Thread* self = Thread::Current();
101 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
Andreas Gampe35439ba2014-08-28 14:41:02 -0700102 if (c->GetVerifyErrorClass() != nullptr) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700103 // TODO: change the verifier to store an _instance_, with a useful detail message?
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700104 std::string temp;
105 self->ThrowNewException(throw_location, c->GetVerifyErrorClass()->GetDescriptor(&temp),
Mathieu Chartierf8322842014-05-16 10:59:25 -0700106 PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700107 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -0800108 self->ThrowNewException(throw_location, "Ljava/lang/NoClassDefFoundError;",
109 PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700110 }
111}
112
Ian Rogers62d6c772013-02-27 08:32:07 -0800113static void WrapExceptionInInitializer() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700114 Thread* self = Thread::Current();
115 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700116
117 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe35439ba2014-08-28 14:41:02 -0700118 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700119
120 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700121 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
122 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700123
Elliott Hughesa4f94742012-05-29 16:28:38 -0700124 // We only wrap non-Error exceptions; an Error can just be used as-is.
125 if (!is_error) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800126 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
Andreas Gampe35439ba2014-08-28 14:41:02 -0700127 self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;",
128 nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700129 }
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700130}
131
Elliott Hughes418d20f2011-09-22 14:00:39 -0700132const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700133 "Ljava/lang/Class;",
134 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700135 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700136 "[Ljava/lang/Object;",
137 "Ljava/lang/String;",
Mathieu Chartier66f19252012-09-18 08:57:04 -0700138 "Ljava/lang/DexCache;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700139 "Ljava/lang/ref/Reference;",
Brian Carlstromea46f952013-07-30 01:26:50 -0700140 "Ljava/lang/reflect/ArtField;",
141 "Ljava/lang/reflect/ArtMethod;",
Ian Rogers466bb252011-10-14 03:29:56 -0700142 "Ljava/lang/reflect/Proxy;",
Mathieu Chartier66f19252012-09-18 08:57:04 -0700143 "[Ljava/lang/String;",
Brian Carlstromea46f952013-07-30 01:26:50 -0700144 "[Ljava/lang/reflect/ArtField;",
145 "[Ljava/lang/reflect/ArtMethod;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700146 "Ljava/lang/ClassLoader;",
Ian Rogers5167c972012-02-03 10:41:20 -0800147 "Ljava/lang/Throwable;",
jeffhao8cd6dda2012-02-22 10:15:34 -0800148 "Ljava/lang/ClassNotFoundException;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700149 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700150 "Z",
151 "B",
152 "C",
153 "D",
154 "F",
155 "I",
156 "J",
157 "S",
158 "V",
159 "[Z",
160 "[B",
161 "[C",
162 "[D",
163 "[F",
164 "[I",
165 "[J",
166 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700167 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700168};
169
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800170ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700171 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700172 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700173 dex_cache_image_class_lookup_required_(false),
174 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800175 class_roots_(nullptr),
176 array_iftable_(nullptr),
177 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700178 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800179 log_new_dex_caches_roots_(false),
180 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700181 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800182 portable_resolution_trampoline_(nullptr),
183 quick_resolution_trampoline_(nullptr),
184 portable_imt_conflict_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800185 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100186 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartiere832e642014-11-10 11:08:06 -0800187 quick_to_interpreter_bridge_trampoline_(nullptr),
188 image_pointer_size_(sizeof(void*)) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700189 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Ian Rogers98379392014-02-24 16:53:16 -0800190 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700191}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700192
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700193// To set a value for generic JNI. May be necessary in compiler tests.
194extern "C" void art_quick_generic_jni_trampoline(mirror::ArtMethod*);
Alex Light507e6182014-08-19 14:23:13 -0700195extern "C" void art_quick_resolution_trampoline(mirror::ArtMethod*);
196extern "C" void art_quick_imt_conflict_trampoline(mirror::ArtMethod*);
197extern "C" void art_quick_to_interpreter_bridge(mirror::ArtMethod*);
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700198
Alex Light507e6182014-08-19 14:23:13 -0700199void ClassLinker::InitWithoutImage(const std::vector<const DexFile*>& boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800200 VLOG(startup) << "ClassLinker::Init";
Alex Light507e6182014-08-19 14:23:13 -0700201 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700202
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700203 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700204
Elliott Hughes30646832011-10-13 16:59:46 -0700205 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700206 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700207 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700208 // 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 -0800209 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700210 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
211 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700212 heap->AllocNonMovableObject<true>(self, nullptr,
213 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700214 VoidFunctor()))));
Andreas Gampe35439ba2014-08-28 14:41:02 -0700215 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700216 mirror::Class::SetClassClass(java_lang_Class.Get());
217 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700218 if (kUseBakerOrBrooksReadBarrier) {
219 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800220 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700221 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800222 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800223 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700224
Elliott Hughes418d20f2011-09-22 14:00:39 -0700225 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700226 Handle<mirror::Class> class_array_class(hs.NewHandle(
227 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700228 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700229
Ian Rogers23435d02012-09-24 11:23:12 -0700230 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700231 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
232 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe35439ba2014-08-28 14:41:02 -0700233 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700234 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700235 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700236 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700237
Ian Rogers23435d02012-09-24 11:23:12 -0700238 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700239 Handle<mirror::Class> object_array_class(hs.NewHandle(
240 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700241 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700242
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700243 // Setup the char (primitive) class to be used for char[].
244 Handle<mirror::Class> char_class(hs.NewHandle(
245 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700246
Ian Rogers23435d02012-09-24 11:23:12 -0700247 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700248 Handle<mirror::Class> char_array_class(hs.NewHandle(
249 AllocClass(self, java_lang_Class.Get(),
250 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700251 char_array_class->SetComponentType(char_class.Get());
252 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700253
Ian Rogers23435d02012-09-24 11:23:12 -0700254 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700255 Handle<mirror::Class> java_lang_String(hs.NewHandle(
256 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700257 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700258 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700259 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400260
Fred Shih4ee7a662014-07-11 09:59:27 -0700261 // Setup Reference.
262 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
263 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
264 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
265 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
266 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
267
Ian Rogers23435d02012-09-24 11:23:12 -0700268 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700269 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
270 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
271 kClassRootsMax));
272 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700273 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
274 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
275 SetClassRoot(kClassArrayClass, class_array_class.Get());
276 SetClassRoot(kObjectArrayClass, object_array_class.Get());
277 SetClassRoot(kCharArrayClass, char_array_class.Get());
278 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700279 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700280
281 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700282 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
283 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
284 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
285 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
286 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
287 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
288 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
289 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700290
Ian Rogers23435d02012-09-24 11:23:12 -0700291 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700292 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700293
Ian Rogers23435d02012-09-24 11:23:12 -0700294 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700295 Handle<mirror::Class> int_array_class(hs.NewHandle(
296 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700297 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700298 mirror::IntArray::SetArrayClass(int_array_class.Get());
299 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700300
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700301 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700302
Ian Rogers52813c92012-10-11 11:50:38 -0700303 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700304 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
305 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700306 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700307 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700308 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700309
Brian Carlstromf3632832014-05-20 15:36:53 -0700310 // Constructor, Field, Method, and AbstractMethod are necessary so
311 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700312 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
313 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Andreas Gampe35439ba2014-08-28 14:41:02 -0700314 CHECK(java_lang_reflect_ArtField.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700315 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700316 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700317 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700318 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700319
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700320 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
321 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe35439ba2014-08-28 14:41:02 -0700322 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Mathieu Chartiere832e642014-11-10 11:08:06 -0800323 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize(sizeof(void*)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700324 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700325 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700326 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700327
328 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700329 Handle<mirror::Class> object_array_string(hs.NewHandle(
330 AllocClass(self, java_lang_Class.Get(),
331 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700332 object_array_string->SetComponentType(java_lang_String.Get());
333 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700334
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700335 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
336 AllocClass(self, java_lang_Class.Get(),
337 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700338 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
339 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700340
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700341 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
342 AllocClass(self, java_lang_Class.Get(),
343 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700344 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
345 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700346
Ian Rogers23435d02012-09-24 11:23:12 -0700347 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
348 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
349 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700350 CHECK_NE(0U, boot_class_path.size());
Mathieu Chartiere832e642014-11-10 11:08:06 -0800351 for (const DexFile* dex_file : boot_class_path) {
Andreas Gampe35439ba2014-08-28 14:41:02 -0700352 CHECK(dex_file != nullptr);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700353 AppendToBootClassPath(*dex_file);
354 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700355
356 // now we can use FindSystemClass
357
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700358 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700359 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
360 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700361
Jeff Hao88474b42013-10-23 16:24:40 -0700362 // Create runtime resolution and imt conflict methods. Also setup the default imt.
363 Runtime* runtime = Runtime::Current();
364 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
365 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier1fb463e2014-10-23 16:48:06 -0700366 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700367 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
368
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700369 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
370 // we do not need friend classes or a publicly exposed setter.
371 quick_generic_jni_trampoline_ = reinterpret_cast<void*>(art_quick_generic_jni_trampoline);
Alex Light507e6182014-08-19 14:23:13 -0700372 if (!runtime->IsCompiler()) {
373 // We need to set up the generic trampolines since we don't have an image.
374 quick_resolution_trampoline_ = reinterpret_cast<void*>(art_quick_resolution_trampoline);
375 quick_imt_conflict_trampoline_ = reinterpret_cast<void*>(art_quick_imt_conflict_trampoline);
376 quick_to_interpreter_bridge_trampoline_ = reinterpret_cast<void*>(art_quick_to_interpreter_bridge);
377 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700378
Mathieu Chartier66f19252012-09-18 08:57:04 -0700379 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700380 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800381 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700382 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700383 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700384 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800385 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700386 std::ostringstream os1, os2;
387 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
388 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
389 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
390 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700391 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800392 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700393 CHECK_EQ(java_lang_String.Get(), String_class);
394 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700395 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700396
Ian Rogers23435d02012-09-24 11:23:12 -0700397 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800398 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800399 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700400
Ian Rogers98379392014-02-24 16:53:16 -0800401 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800402 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700403
Ian Rogers98379392014-02-24 16:53:16 -0800404 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700405 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700406
Ian Rogers98379392014-02-24 16:53:16 -0800407 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800408 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700409
Ian Rogers98379392014-02-24 16:53:16 -0800410 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700411 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700412
Ian Rogers98379392014-02-24 16:53:16 -0800413 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800414 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700415
Ian Rogers98379392014-02-24 16:53:16 -0800416 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800417 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700418
Ian Rogers98379392014-02-24 16:53:16 -0800419 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800420 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700421
Ian Rogers98379392014-02-24 16:53:16 -0800422 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700423 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700424
Ian Rogers98379392014-02-24 16:53:16 -0800425 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700426 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700427
Ian Rogers23435d02012-09-24 11:23:12 -0700428 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800429 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe35439ba2014-08-28 14:41:02 -0700430 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800431 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe35439ba2014-08-28 14:41:02 -0700432 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700433 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
434 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700435 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700436 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700437 array_iftable->SetInterface(0, java_lang_Cloneable);
438 array_iftable->SetInterface(1, java_io_Serializable);
439 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700440
Ian Rogers23435d02012-09-24 11:23:12 -0700441 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700442 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
443 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
444 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
445 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700446 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700447 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800448 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700449 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700450
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700451 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800452 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700453 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700454
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700455 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800456 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700457 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700458
Brian Carlstromf3632832014-05-20 15:36:53 -0700459 mirror::Class* String_array_class =
460 FindSystemClass(self, class_roots_descriptors_[kJavaLangStringArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700461 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700462
Brian Carlstromea46f952013-07-30 01:26:50 -0700463 mirror::Class* Art_method_array_class =
Ian Rogers98379392014-02-24 16:53:16 -0800464 FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700465 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700466
Brian Carlstromea46f952013-07-30 01:26:50 -0700467 mirror::Class* Art_field_array_class =
Ian Rogers98379392014-02-24 16:53:16 -0800468 FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700469 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700470
Ian Rogers23435d02012-09-24 11:23:12 -0700471 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700472
Ian Rogers23435d02012-09-24 11:23:12 -0700473 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800474 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700475 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
476
Brian Carlstrom1f870082011-08-23 16:02:11 -0700477 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700478 // finish initializing Reference class
479 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
480 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
481 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
482 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
483 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700484 mirror::Class* java_lang_ref_FinalizerReference =
485 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700486 java_lang_ref_FinalizerReference->SetAccessFlags(
487 java_lang_ref_FinalizerReference->GetAccessFlags() |
488 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700489 mirror::Class* java_lang_ref_PhantomReference =
490 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700491 java_lang_ref_PhantomReference->SetAccessFlags(
492 java_lang_ref_PhantomReference->GetAccessFlags() |
493 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700494 mirror::Class* java_lang_ref_SoftReference =
495 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700496 java_lang_ref_SoftReference->SetAccessFlags(
497 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700498 mirror::Class* java_lang_ref_WeakReference =
499 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700500 java_lang_ref_WeakReference->SetAccessFlags(
501 java_lang_ref_WeakReference->GetAccessFlags() |
502 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700503
Ian Rogers23435d02012-09-24 11:23:12 -0700504 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800505 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700506 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700507 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
508
jeffhao8cd6dda2012-02-22 10:15:34 -0800509 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700510 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800511 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800512 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700513 SetClassRoot(kJavaLangClassNotFoundException,
514 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800515 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700516 SetClassRoot(kJavaLangStackTraceElementArrayClass,
517 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800518 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700519
Sebastien Hertzcad417c2014-12-09 19:08:15 +0100520 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
521 // initialized.
522 {
523 const DexFile& dex_file = java_lang_Object->GetDexFile();
524 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
525 CHECK(void_string_id != nullptr);
526 uint32_t void_string_index = dex_file.GetIndexForStringId(*void_string_id);
527 const DexFile::TypeId* void_type_id = dex_file.FindTypeId(void_string_index);
528 CHECK(void_type_id != nullptr);
529 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
530 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
531 // as referrer so the used dex cache is core's one.
532 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
533 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
534 self->AssertNoPendingException();
535 }
536
Ian Rogers98379392014-02-24 16:53:16 -0800537 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700538
Brian Carlstroma004aa92012-02-08 18:05:09 -0800539 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700540}
541
Ian Rogers98379392014-02-24 16:53:16 -0800542void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800543 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700544
545 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700546 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700547 // as the types of the field can't be resolved prior to the runtime being
548 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800549 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700550 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800551 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800552
Brian Carlstromea46f952013-07-30 01:26:50 -0700553 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700554 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
555 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700556
Brian Carlstromea46f952013-07-30 01:26:50 -0700557 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700558 CHECK_STREQ(queue->GetName(), "queue");
559 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700560
Brian Carlstromea46f952013-07-30 01:26:50 -0700561 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700562 CHECK_STREQ(queueNext->GetName(), "queueNext");
563 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700564
Brian Carlstromea46f952013-07-30 01:26:50 -0700565 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700566 CHECK_STREQ(referent->GetName(), "referent");
567 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700568
Brian Carlstromea46f952013-07-30 01:26:50 -0700569 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700570 CHECK_STREQ(zombie->GetName(), "zombie");
571 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700572
Brian Carlstroma663ea52011-08-19 23:33:41 -0700573 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700574 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700575 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800576 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe35439ba2014-08-28 14:41:02 -0700577 CHECK(klass != nullptr);
578 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700579 // note SetClassRoot does additional validation.
580 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700581 }
582
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700583 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700584
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700585 // disable the slow paths in FindClass and CreatePrimitiveClass now
586 // that Object, Class, and Object[] are setup
587 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700588
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800589 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700590}
591
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700592void ClassLinker::RunRootClinits() {
593 Thread* self = Thread::Current();
594 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800595 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700596 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700597 StackHandleScope<1> hs(self);
598 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
599 EnsureInitialized(h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700600 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700601 }
602 }
603}
604
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700605bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800606 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000607 const char* oat_cache_filename,
608 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700609 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700610 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800611
Ian Rogers1d54e732013-05-02 21:10:01 -0700612 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800613 std::string boot_image_option("--boot-image=");
Alex Light507e6182014-08-19 14:23:13 -0700614 if (heap->GetImageSpace() == nullptr) {
615 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
616 // out of space anyway it might not matter.
617 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
618 "without an image.", dex_filename);
619 return false;
620 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700621 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800622
Brian Carlstrom6449c622014-02-10 23:48:36 -0800623 std::string dex_file_option("--dex-file=");
624 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800625
Brian Carlstrom6449c622014-02-10 23:48:36 -0800626 std::string oat_fd_option("--oat-fd=");
627 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800628
Brian Carlstrom6449c622014-02-10 23:48:36 -0800629 std::string oat_location_option("--oat-location=");
630 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800631
Brian Carlstrom6449c622014-02-10 23:48:36 -0800632 std::vector<std::string> argv;
633 argv.push_back(dex2oat);
634 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800635 argv.push_back("-classpath");
636 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800637 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800638
Ian Rogers8afeb852014-04-02 14:55:49 -0700639 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800640
Jeff Hao4a200f52014-04-01 14:58:49 -0700641 if (!Runtime::Current()->IsVerificationEnabled()) {
642 argv.push_back("--compiler-filter=verify-none");
643 }
644
Alex Light345c4b12014-07-18 14:57:04 -0700645 if (Runtime::Current()->MustRelocateIfPossible()) {
646 argv.push_back("--runtime-arg");
647 argv.push_back("-Xrelocate");
648 } else {
649 argv.push_back("--runtime-arg");
650 argv.push_back("-Xnorelocate");
651 }
652
Brian Carlstrom6449c622014-02-10 23:48:36 -0800653 if (!kIsTargetBuild) {
654 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700655 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700656
Brian Carlstrom6449c622014-02-10 23:48:36 -0800657 argv.push_back(boot_image_option);
658 argv.push_back(dex_file_option);
659 argv.push_back(oat_fd_option);
660 argv.push_back(oat_location_option);
661 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800662 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800663 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700664 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800665
Andreas Gampead00fed2014-12-10 20:51:45 -0800666 if (!Exec(argv, error_msg)) {
667 // Manually delete the file. Ensures there is no garbage left over if the process unexpectedly
668 // died. Ignore unlink failure, propagate the original error.
669 TEMP_FAILURE_RETRY(unlink(oat_cache_filename));
670 return false;
671 }
672
673 return true;
jeffhao262bf462011-10-20 18:36:32 -0700674}
675
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700676const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700677 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800678 if (kIsDebugBuild) {
679 for (size_t i = 0; i < oat_files_.size(); ++i) {
680 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700681 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800682 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700683 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
684 oat_files_.push_back(oat_file);
685 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800686}
687
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700688OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
689 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700690 OatFile* oat_file = space->ReleaseOatFile();
691 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700692 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700693 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700694}
695
Vladimir Markobe4e6432014-09-05 14:01:17 +0100696const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800697 const char* dex_location = dex_file.GetLocation().c_str();
698 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markobe4e6432014-09-05 14:01:17 +0100699 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800700}
701
Vladimir Markobe4e6432014-09-05 14:01:17 +0100702const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
703 const char* dex_location,
704 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700705 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markobe4e6432014-09-05 14:01:17 +0100706 for (const OatFile* oat_file : oat_files_) {
707 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700708
709 if (oat_location != nullptr) {
710 if (oat_file->GetLocation() != oat_location) {
711 continue;
712 }
713 }
714
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700715 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800716 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700717 false);
Vladimir Markobe4e6432014-09-05 14:01:17 +0100718 if (oat_dex_file != nullptr) {
719 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800720 }
721 }
Vladimir Markobe4e6432014-09-05 14:01:17 +0100722 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800723}
724
Calin Juravleca345932014-09-02 15:53:55 +0100725
726// Loads all multi dex files from the given oat file returning true on success.
727//
728// Parameters:
729// oat_file - the oat file to load from
730// dex_location - the dex location used to generate the oat file
731// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
732// generated - whether or not the oat_file existed before or was just (re)generated
733// error_msgs - any error messages will be appended here
734// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
735static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
736 const char* dex_location,
737 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700738 bool generated,
739 std::vector<std::string>* error_msgs,
740 std::vector<const DexFile*>* dex_files) {
741 if (oat_file == nullptr) {
742 return false;
743 }
744
745 size_t old_size = dex_files->size(); // To rollback on error.
746
747 bool success = true;
748 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100749 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700750 const char* next_name = next_name_str.c_str();
751
Calin Juravleca345932014-09-02 15:53:55 +0100752 uint32_t next_location_checksum;
753 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700754 std::string error_msg;
Calin Juravleca345932014-09-02 15:53:55 +0100755 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
756 // When i=0 the multidex name should be the same as the location name. We already have the
757 // checksum it so we don't need to recompute it.
758 if (dex_location_checksum == nullptr) {
759 next_location_checksum_pointer = nullptr;
760 } else {
761 next_location_checksum = *dex_location_checksum;
762 }
763 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700764 DCHECK_EQ(false, i == 0 && generated);
Calin Juravleca345932014-09-02 15:53:55 +0100765 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700766 }
767
768 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
769
770 if (oat_dex_file == nullptr) {
771 if (i == 0 && generated) {
772 std::string error_msg;
773 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravleca345932014-09-02 15:53:55 +0100774 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700775 oat_file->GetLocation().c_str());
776 error_msgs->push_back(error_msg);
777 }
778 break; // Not found, done.
779 }
780
781 // Checksum test. Test must succeed when generated.
782 success = !generated;
Calin Juravleca345932014-09-02 15:53:55 +0100783 if (next_location_checksum_pointer != nullptr) {
784 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700785 }
786
787 if (success) {
788 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
789 if (dex_file == nullptr) {
790 success = false;
791 error_msgs->push_back(error_msg);
792 } else {
793 dex_files->push_back(dex_file);
794 }
795 }
796
797 // When we generated the file, we expect success, or something is terribly wrong.
798 CHECK_EQ(false, generated && !success)
799 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravleca345932014-09-02 15:53:55 +0100800 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700801 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
802 }
803
804 if (dex_files->size() == old_size) {
805 success = false; // We did not even find classes.dex
806 }
807
808 if (success) {
809 return true;
810 } else {
811 // Free all the dex files we have loaded.
812 auto it = dex_files->begin() + old_size;
813 auto it_end = dex_files->end();
814 for (; it != it_end; it++) {
815 delete *it;
816 }
817 dex_files->erase(dex_files->begin() + old_size, it_end);
818
819 return false;
820 }
821}
822
823// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
824// complicates the loading process, as we should not use an iterative loading process, because that
825// would register the oat file and dex files that come before the broken one. Instead, check all
826// multidex ahead of time.
827bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
828 std::vector<std::string>* error_msgs,
829 std::vector<const DexFile*>* dex_files) {
830 // 1) Check whether we have an open oat file.
831 // This requires a dex checksum, use the "primary" one.
832 uint32_t dex_location_checksum;
833 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
834 bool have_checksum = true;
835 std::string checksum_error_msg;
836 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravleca345932014-09-02 15:53:55 +0100837 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700838 dex_location_checksum_pointer = nullptr;
839 have_checksum = false;
840 }
841
842 bool needs_registering = false;
843
Vladimir Markobe4e6432014-09-05 14:01:17 +0100844 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
845 dex_location_checksum_pointer);
846 std::unique_ptr<const OatFile> open_oat_file(
847 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700848
849 // 2) If we do not have an open one, maybe there's one on disk already.
850
851 // In case the oat file is not open, we play a locking game here so
852 // that if two different processes race to load and register or generate
853 // (or worse, one tries to open a partial generated file) we will be okay.
854 // This is actually common with apps that use DexClassLoader to work
855 // around the dex method reference limit and that have a background
856 // service running in a separate process.
857 ScopedFlock scoped_flock;
858
859 if (open_oat_file.get() == nullptr) {
860 if (oat_location != nullptr) {
861 // Can only do this if we have a checksum, else error.
862 if (!have_checksum) {
863 error_msgs->push_back(checksum_error_msg);
864 return false;
865 }
866
867 std::string error_msg;
868
869 // We are loading or creating one in the future. Time to set up the file lock.
870 if (!scoped_flock.Init(oat_location, &error_msg)) {
871 error_msgs->push_back(error_msg);
872 return false;
873 }
874
Alex Lighta59dd802014-07-02 16:28:08 -0700875 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700876 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
877 oat_location, &error_msg));
878
879 if (open_oat_file.get() == nullptr) {
880 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
881 dex_location, oat_location, error_msg.c_str());
882 VLOG(class_linker) << compound_msg;
883 error_msgs->push_back(compound_msg);
884 }
885 } else {
886 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100887 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700888 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
889 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100890 kRuntimeISA, error_msgs,
891 &obsolete_file_cleanup_failed));
892 // There's no point in going forward and eventually try to regenerate the
893 // file if we couldn't remove the obsolete one. Mostly likely we will fail
894 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100895 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
896 if (obsolete_file_cleanup_failed) {
897 return false;
898 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700899 }
900 needs_registering = true;
901 }
902
903 // 3) If we have an oat file, check all contained multidex files for our dex_location.
904 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravleca345932014-09-02 15:53:55 +0100905 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
906 dex_location_checksum_pointer,
907 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700908 if (success) {
909 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
910 if (needs_registering) {
911 // We opened the oat file, so we must register it.
912 RegisterOatFile(oat_file);
913 }
Alex Light0a112bb2014-08-14 14:16:26 -0700914 // If the file isn't executable we failed patchoat but did manage to get the dex files.
915 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700916 } else {
917 if (needs_registering) {
918 // We opened it, delete it.
919 open_oat_file.reset();
920 } else {
921 open_oat_file.release(); // Do not delete open oat files.
922 }
923 }
924
925 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
926
927 // Need a checksum, fail else.
928 if (!have_checksum) {
929 error_msgs->push_back(checksum_error_msg);
930 return false;
931 }
932
933 // Look in cache location if no oat_location is given.
934 std::string cache_location;
935 if (oat_location == nullptr) {
936 // Use the dalvik cache.
937 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
938 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
939 oat_location = cache_location.c_str();
940 }
941
Alex Light507e6182014-08-19 14:23:13 -0700942 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -0700943 // Definitely need to lock now.
944 if (!scoped_flock.HasFile()) {
945 std::string error_msg;
946 if (!scoped_flock.Init(oat_location, &error_msg)) {
947 error_msgs->push_back(error_msg);
Alex Light507e6182014-08-19 14:23:13 -0700948 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -0700949 }
950 }
951
Alex Light507e6182014-08-19 14:23:13 -0700952 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray9c290012014-07-22 10:48:00 +0100953 // Create the oat file.
954 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
955 oat_location, error_msgs));
956 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700957
958 // Failed, bail.
959 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray9c290012014-07-22 10:48:00 +0100960 std::string error_msg;
961 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
962 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
963 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -0700964 return false;
965 }
966
967 // Try to load again, but stronger checks.
Vladimir Markobe4e6432014-09-05 14:01:17 +0100968 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
969 dex_location_checksum_pointer,
Calin Juravleca345932014-09-02 15:53:55 +0100970 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700971 if (success) {
972 RegisterOatFile(open_oat_file.release());
973 return true;
974 } else {
975 return false;
976 }
977}
978
979const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
980 uint32_t dex_location_checksum,
981 const char* oat_location,
982 std::string* error_msg) {
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700983 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700984 !Runtime::Current()->IsCompiler(),
985 error_msg));
986 if (oat_file.get() == nullptr) {
987 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
988 error_msg->c_str());
989 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800990 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700991 Runtime* runtime = Runtime::Current();
Alex Light496cd332014-08-29 10:28:25 -0700992 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
993 if (image_space != nullptr) {
994 const ImageHeader& image_header = image_space->GetImageHeader();
995 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
996 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
997 if (expected_image_oat_checksum != actual_image_oat_checksum) {
998 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
999 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1000 actual_image_oat_checksum);
1001 return nullptr;
1002 }
1003
1004 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1005 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1006 if (expected_image_oat_offset != actual_image_oat_offset) {
1007 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1008 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1009 actual_image_oat_offset);
1010 return nullptr;
1011 }
1012 int32_t expected_patch_delta = image_header.GetPatchDelta();
1013 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1014 if (expected_patch_delta != actual_patch_delta) {
1015 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1016 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1017 return nullptr;
1018 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001019 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001020
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001021 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1022 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001023 if (oat_dex_file == nullptr) {
1024 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1025 dex_location);
1026 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001027 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001028 uint32_t expected_dex_checksum = dex_location_checksum;
1029 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1030 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001031 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1032 "found 0x%x", oat_location, expected_dex_checksum,
1033 actual_dex_checksum);
1034 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001035 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001036 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1037 if (dex_file.get() != nullptr) {
1038 return oat_file.release();
1039 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001040 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001041 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001042}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001043
Andreas Gampe833a4852014-05-21 18:46:59 -07001044const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1045 int fd, const char* oat_location,
1046 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001047 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001048 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001049 std::string error_msg;
1050 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001051 CHECK(!error_msg.empty());
1052 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001053 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001054 }
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001055 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001056 !Runtime::Current()->IsCompiler(),
1057 &error_msg));
1058 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001059 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1060 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001061 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001062 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001063 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001064
1065 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001066}
1067
Alex Light345c4b12014-07-18 14:57:04 -07001068bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1069 const InstructionSet instruction_set) {
1070 Runtime* runtime = Runtime::Current();
1071 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light507e6182014-08-19 14:23:13 -07001072 if (image_space == nullptr) {
1073 return false;
1074 }
Alex Light345c4b12014-07-18 14:57:04 -07001075 uint32_t image_oat_checksum = 0;
1076 if (instruction_set == kRuntimeISA) {
1077 const ImageHeader& image_header = image_space->GetImageHeader();
1078 image_oat_checksum = image_header.GetOatChecksum();
1079 } else {
1080 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1081 image_space->GetImageLocation().c_str(), instruction_set));
1082 image_oat_checksum = image_header->GetOatChecksum();
1083 }
1084 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1085}
1086
1087bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1088 const InstructionSet instruction_set,
1089 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001090 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001091 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light507e6182014-08-19 14:23:13 -07001092 if (image_space == nullptr) {
1093 *error_msg = "No image space for verification against";
1094 return false;
1095 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001096
1097 // If the requested instruction set is the same as the current runtime,
1098 // we can use the checksums directly. If it isn't, we'll have to read the
1099 // image header from the image for the right instruction set.
1100 uint32_t image_oat_checksum = 0;
1101 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001102 int32_t image_patch_delta = 0;
Brian Carlstrom95a93542014-09-29 11:22:54 -07001103 if (instruction_set == runtime->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001104 const ImageHeader& image_header = image_space->GetImageHeader();
1105 image_oat_checksum = image_header.GetOatChecksum();
1106 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001107 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001108 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001109 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001110 image_space->GetImageLocation().c_str(), instruction_set));
1111 image_oat_checksum = image_header->GetOatChecksum();
1112 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001113 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001114 }
1115 const OatHeader& oat_header = oat_file->GetOatHeader();
Igor Murashkin5ef29902014-10-29 19:45:42 -07001116 bool ret = (oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum);
1117
1118 // If the oat file is PIC, it doesn't care if/how image was relocated. Ignore these checks.
1119 if (!oat_file->IsPic()) {
1120 ret = ret && (oat_header.GetImagePatchDelta() == image_patch_delta)
1121 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin);
1122 }
Alex Light345c4b12014-07-18 14:57:04 -07001123 if (!ret) {
1124 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1125 oat_file->GetLocation().c_str(),
1126 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1127 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1128 oat_file->GetOatHeader().GetImagePatchDelta(),
1129 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1130 }
1131 return ret;
1132}
1133
1134bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1135 const char* dex_location,
1136 uint32_t dex_location_checksum,
1137 const InstructionSet instruction_set,
1138 std::string* error_msg) {
1139 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1140 return false;
1141 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001142
Brian Carlstromf3632832014-05-20 15:36:53 -07001143 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1144 &dex_location_checksum);
Andreas Gampe35439ba2014-08-28 14:41:02 -07001145 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001146 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1147 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Vladimir Markobe4e6432014-09-05 14:01:17 +01001148 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
1149 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001150 oat_file->GetLocation().c_str(),
Vladimir Markobe4e6432014-09-05 14:01:17 +01001151 oat_dex_file->GetDexFileLocation().c_str(),
1152 oat_dex_file->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001153 }
1154 return false;
1155 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001156
Alex Light345c4b12014-07-18 14:57:04 -07001157 if (dex_location_checksum != oat_dex_file->GetDexFileLocationChecksum()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001158 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x) with '%s' (0x%x)",
1159 oat_file->GetLocation().c_str(),
1160 oat_dex_file->GetDexFileLocationChecksum(),
1161 dex_location, dex_location_checksum);
Alex Light345c4b12014-07-18 14:57:04 -07001162 return false;
Brian Carlstromafe25512012-06-27 17:02:58 -07001163 }
Alex Light345c4b12014-07-18 14:57:04 -07001164 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001165}
1166
Alex Lighta59dd802014-07-02 16:28:08 -07001167bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1168 const char* dex_location,
Calin Juravleca345932014-09-02 15:53:55 +01001169 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001170 std::string* error_msg) {
1171 CHECK(oat_file != nullptr);
1172 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001173 std::unique_ptr<const DexFile> dex_file;
Calin Juravleca345932014-09-02 15:53:55 +01001174 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001175 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1176 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1177 // directory.
Andreas Gampe35439ba2014-08-28 14:41:02 -07001178 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001179 if (oat_dex_file == nullptr) {
1180 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001181 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001182 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001183 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001184 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001185 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001186 } else {
Calin Juravleca345932014-09-02 15:53:55 +01001187 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light345c4b12014-07-18 14:57:04 -07001188 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001189 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001190 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001191 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001192 dex_file.reset(oat_file->GetOatDexFile(dex_location,
Calin Juravleca345932014-09-02 15:53:55 +01001193 dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001194 }
Alex Lighta59dd802014-07-02 16:28:08 -07001195 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001196}
1197
Andreas Gampe833a4852014-05-21 18:46:59 -07001198const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001199 const char* dex_location,
Vladimir Markobe4e6432014-09-05 14:01:17 +01001200 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001201 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001202 std::vector<std::string>* error_msgs,
1203 bool* obsolete_file_cleanup_failed) {
1204 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001205 bool already_opened = false;
1206 std::string dex_location_str(dex_location);
1207 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1208 &already_opened,
1209 obsolete_file_cleanup_failed,
1210 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001211 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001212 if (oat_file.get() == nullptr) {
1213 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1214 dex_location));
1215 return nullptr;
Alex Light0a112bb2014-08-14 14:16:26 -07001216 } else if (oat_file->IsExecutable() &&
Calin Juravleca345932014-09-02 15:53:55 +01001217 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1218 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001219 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1220 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001221 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001222 return nullptr;
Alex Light0a112bb2014-08-14 14:16:26 -07001223 } else if (!oat_file->IsExecutable() &&
Alex Lightfb777592014-08-22 17:49:35 -07001224 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light0a112bb2014-08-14 14:16:26 -07001225 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1226 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1227 "dex location '%s'. Image checksum incorrect.",
1228 oat_file->GetLocation().c_str(), dex_location));
1229 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001230 } else {
1231 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001232 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001233}
1234
Brian Carlstromae826982011-11-09 01:33:42 -08001235const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001236 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001237 for (size_t i = 0; i < oat_files_.size(); i++) {
1238 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001239 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001240 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001241 return oat_file;
1242 }
1243 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001244 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001245}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001246
Alex Lighta59dd802014-07-02 16:28:08 -07001247const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1248 InstructionSet isa,
1249 bool *already_opened,
1250 bool *obsolete_file_cleanup_failed,
1251 std::vector<std::string>* error_msgs) {
1252 // Find out if we've already opened the file
1253 const OatFile* ret = nullptr;
1254 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1255 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1256 if (ret != nullptr) {
1257 *already_opened = true;
1258 return ret;
1259 }
1260
1261 std::string dalvik_cache;
1262 bool have_android_data = false;
1263 bool have_dalvik_cache = false;
Andreas Gampe33c36d42014-09-18 20:56:04 -07001264 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001265 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe33c36d42014-09-18 20:56:04 -07001266 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001267 std::string cache_filename;
1268 if (have_dalvik_cache) {
1269 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1270 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1271 if (ret != nullptr) {
1272 *already_opened = true;
1273 return ret;
1274 }
1275 } else {
1276 // If we need to relocate we should just place odex back where it started.
1277 cache_filename = odex_filename;
1278 }
1279
1280 ret = nullptr;
1281
1282 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1283 //
1284 // Now we do the following:
1285 // 1) Try and open the odex version
1286 // 2) If present, checksum-verified & relocated correctly return it
1287 // 3) Close the odex version to free up its address space.
1288 // 4) Try and open the cache version
1289 // 5) If present, checksum-verified & relocated correctly return it
1290 // 6) Close the cache version to free up its address space.
1291 // 7) If we should relocate:
1292 // a) If we have opened and checksum-verified the odex version relocate it to
1293 // 'cache_filename' and return it
1294 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1295 // it. This should not happen often (I think only the run-test's will hit this case).
1296 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1297 // this point.
1298 // 9) Return nullptr
1299
1300 *already_opened = false;
1301 const Runtime* runtime = Runtime::Current();
1302 CHECK(runtime != nullptr);
1303 bool executable = !runtime->IsCompiler();
1304
1305 std::string odex_error_msg;
1306 bool should_patch_system = false;
1307 bool odex_checksum_verified = false;
Alex Lightfb777592014-08-22 17:49:35 -07001308 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001309 {
Andreas Gamped7392fa2014-10-23 11:37:40 -07001310 // There is a high probability that both these oat files map similar/the same address
Alex Lighta59dd802014-07-02 16:28:08 -07001311 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe35439ba2014-08-28 14:41:02 -07001312 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001313 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001314 executable, &odex_error_msg));
Andreas Gamped7392fa2014-10-23 11:37:40 -07001315 if (odex_oat_file.get() != nullptr && CheckOatFile(runtime, odex_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001316 &odex_checksum_verified,
1317 &odex_error_msg)) {
1318 error_msgs->push_back(odex_error_msg);
1319 return odex_oat_file.release();
Alex Lightfb777592014-08-22 17:49:35 -07001320 } else {
1321 if (odex_checksum_verified) {
1322 // We can just relocate
1323 should_patch_system = true;
1324 odex_error_msg = "Image Patches are incorrect";
1325 }
1326 if (odex_oat_file.get() != nullptr) {
1327 have_system_odex = true;
1328 }
Alex Lighta59dd802014-07-02 16:28:08 -07001329 }
1330 }
1331
Alex Lighta59dd802014-07-02 16:28:08 -07001332 std::string cache_error_msg;
1333 bool should_patch_cache = false;
1334 bool cache_checksum_verified = false;
1335 if (have_dalvik_cache) {
Andreas Gampe35439ba2014-08-28 14:41:02 -07001336 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001337 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001338 executable, &cache_error_msg));
Andreas Gamped7392fa2014-10-23 11:37:40 -07001339 if (cache_oat_file.get() != nullptr && CheckOatFile(runtime, cache_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001340 &cache_checksum_verified,
1341 &cache_error_msg)) {
1342 error_msgs->push_back(cache_error_msg);
1343 return cache_oat_file.release();
1344 } else if (cache_checksum_verified) {
1345 // We can just relocate
1346 should_patch_cache = true;
1347 cache_error_msg = "Image Patches are incorrect";
1348 }
1349 } else if (have_android_data) {
1350 // dalvik_cache does not exist but android data does. This means we should be able to create
1351 // it, so we should try.
1352 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1353 }
1354
1355 ret = nullptr;
1356 std::string error_msg;
1357 if (runtime->CanRelocate()) {
1358 // Run relocation
Alex Light507e6182014-08-19 14:23:13 -07001359 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1360 if (space != nullptr) {
1361 const std::string& image_location = space->GetImageLocation();
1362 if (odex_checksum_verified && should_patch_system) {
1363 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1364 } else if (cache_checksum_verified && should_patch_cache) {
1365 CHECK(have_dalvik_cache);
1366 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1367 }
Alex Lightfb777592014-08-22 17:49:35 -07001368 } else if (have_system_odex) {
1369 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001370 }
1371 }
1372 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1373 // implicitly: were able to fine where the cached version is but we were unable to use it,
1374 // either as a destination for relocation or to open a file. We should delete it if it is
1375 // there.
1376 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1377 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1378 "searching for dex file %s: %s",
1379 cache_filename.c_str(), dex_location.c_str(),
1380 strerror(errno));
1381 error_msgs->push_back(rm_error_msg);
1382 VLOG(class_linker) << rm_error_msg;
1383 // Let the caller know that we couldn't remove the obsolete file.
1384 // This is a good indication that further writes may fail as well.
1385 *obsolete_file_cleanup_failed = true;
1386 }
1387 }
1388 if (ret == nullptr) {
1389 VLOG(class_linker) << error_msg;
1390 error_msgs->push_back(error_msg);
1391 std::string relocation_msg;
1392 if (runtime->CanRelocate()) {
1393 relocation_msg = StringPrintf(" and relocation failed");
1394 }
1395 if (have_dalvik_cache && cache_checksum_verified) {
1396 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1397 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1398 cache_filename.c_str(), cache_error_msg.c_str(),
1399 relocation_msg.c_str());
1400 } else {
1401 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1402 "dalvik_cache availible)%s.", odex_filename.c_str(),
1403 odex_error_msg.c_str(), relocation_msg.c_str());
1404 }
1405 VLOG(class_linker) << error_msg;
1406 error_msgs->push_back(error_msg);
1407 }
1408 return ret;
1409}
1410
Alex Light0a112bb2014-08-14 14:16:26 -07001411const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1412 InstructionSet isa,
1413 std::string* error_msg) {
1414 // We open it non-executable
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001415 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, nullptr, false, error_msg));
Alex Light0a112bb2014-08-14 14:16:26 -07001416 if (output.get() == nullptr) {
1417 return nullptr;
1418 }
Alex Lightfb777592014-08-22 17:49:35 -07001419 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1420 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light0a112bb2014-08-14 14:16:26 -07001421 return output.release();
1422 } else {
1423 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1424 oat_path.c_str());
1425 return nullptr;
1426 }
1427}
1428
Alex Lighta59dd802014-07-02 16:28:08 -07001429const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1430 const std::string& output_oat,
1431 const std::string& image_location,
1432 InstructionSet isa,
1433 std::string* error_msg) {
Andreas Gamped7392fa2014-10-23 11:37:40 -07001434 Runtime* runtime = Runtime::Current();
1435 DCHECK(runtime != nullptr);
1436 if (!runtime->GetHeap()->HasImageSpace()) {
Alex Light507e6182014-08-19 14:23:13 -07001437 // We don't have an image space so there is no point in trying to patchoat.
1438 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1439 << "running without an image. Attempting to use oat file for interpretation.";
1440 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1441 }
Andreas Gamped7392fa2014-10-23 11:37:40 -07001442 if (!runtime->IsDex2OatEnabled()) {
Alex Light0a112bb2014-08-14 14:16:26 -07001443 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1444 // input_oat but make sure we only do interpretation on it's dex files.
1445 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1446 << "disabled. Attempting to use oat file for interpretation";
1447 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1448 }
Alex Lighta59dd802014-07-02 16:28:08 -07001449 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Andreas Gamped7392fa2014-10-23 11:37:40 -07001450 std::string patchoat(runtime->GetPatchoatExecutable());
Alex Lighta59dd802014-07-02 16:28:08 -07001451
1452 std::string isa_arg("--instruction-set=");
1453 isa_arg += GetInstructionSetString(isa);
1454 std::string input_oat_filename_arg("--input-oat-file=");
1455 input_oat_filename_arg += input_oat;
1456 std::string output_oat_filename_arg("--output-oat-file=");
1457 output_oat_filename_arg += output_oat;
1458 std::string patched_image_arg("--patched-image-location=");
1459 patched_image_arg += image_location;
1460
1461 std::vector<std::string> argv;
1462 argv.push_back(patchoat);
1463 argv.push_back(isa_arg);
1464 argv.push_back(input_oat_filename_arg);
1465 argv.push_back(output_oat_filename_arg);
1466 argv.push_back(patched_image_arg);
1467
1468 std::string command_line(Join(argv, ' '));
1469 LOG(INFO) << "Relocate Oat File: " << command_line;
1470 bool success = Exec(argv, error_msg);
1471 if (success) {
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001472 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr, nullptr,
Andreas Gamped7392fa2014-10-23 11:37:40 -07001473 !runtime->IsCompiler(), error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001474 bool checksum_verified = false;
Andreas Gamped7392fa2014-10-23 11:37:40 -07001475 if (output.get() != nullptr && CheckOatFile(runtime, output.get(), isa, &checksum_verified,
1476 error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001477 return output.release();
1478 } else if (output.get() != nullptr) {
1479 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1480 "but output file '%s' failed verifcation: %s",
1481 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1482 } else {
1483 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1484 "but was unable to open output file '%s': %s",
1485 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1486 }
Andreas Gamped7392fa2014-10-23 11:37:40 -07001487 } else if (!runtime->IsCompiler()) {
Alex Light0a112bb2014-08-14 14:16:26 -07001488 // patchoat failed which means we probably don't have enough room to place the output oat file,
1489 // instead of failing we should just run the interpreter from the dex files in the input oat.
1490 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1491 << "for interpretation. patchoat failure was: " << *error_msg;
1492 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001493 } else {
1494 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1495 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1496 error_msg->c_str());
1497 }
1498 return nullptr;
1499}
1500
Andreas Gamped7392fa2014-10-23 11:37:40 -07001501bool ClassLinker::CheckOatFile(const Runtime* runtime, const OatFile* oat_file, InstructionSet isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001502 bool* checksum_verified,
1503 std::string* error_msg) {
1504 std::string compound_msg("Oat file failed to verify: ");
Alex Lighta59dd802014-07-02 16:28:08 -07001505 uint32_t real_image_checksum;
1506 void* real_image_oat_offset;
1507 int32_t real_patch_delta;
Andreas Gamped7392fa2014-10-23 11:37:40 -07001508 const gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
Alex Light507e6182014-08-19 14:23:13 -07001509 if (image_space == nullptr) {
1510 *error_msg = "No image space present";
1511 return false;
1512 }
Alex Lighta59dd802014-07-02 16:28:08 -07001513 if (isa == Runtime::Current()->GetInstructionSet()) {
1514 const ImageHeader& image_header = image_space->GetImageHeader();
1515 real_image_checksum = image_header.GetOatChecksum();
1516 real_image_oat_offset = image_header.GetOatDataBegin();
1517 real_patch_delta = image_header.GetPatchDelta();
1518 } else {
1519 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1520 image_space->GetImageLocation().c_str(), isa));
1521 real_image_checksum = image_header->GetOatChecksum();
1522 real_image_oat_offset = image_header->GetOatDataBegin();
1523 real_patch_delta = image_header->GetPatchDelta();
1524 }
1525
1526 const OatHeader& oat_header = oat_file->GetOatHeader();
1527
1528 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1529 *checksum_verified = oat_image_checksum == real_image_checksum;
1530 if (!*checksum_verified) {
1531 compound_msg += StringPrintf(" Oat Image Checksum Incorrect (expected 0x%x, recieved 0x%x)",
1532 real_image_checksum, oat_image_checksum);
1533 }
1534
Andreas Gamped7392fa2014-10-23 11:37:40 -07001535 bool offset_verified;
1536 bool patch_delta_verified;
Alex Lighta59dd802014-07-02 16:28:08 -07001537
Andreas Gamped7392fa2014-10-23 11:37:40 -07001538 if (!oat_file->IsPic()) {
1539 void* oat_image_oat_offset =
1540 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1541 offset_verified = oat_image_oat_offset == real_image_oat_offset;
1542 if (!offset_verified) {
1543 compound_msg += StringPrintf(" Oat Image oat offset incorrect (expected 0x%p, recieved 0x%p)",
1544 real_image_oat_offset, oat_image_oat_offset);
1545 }
1546
1547 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1548 patch_delta_verified = oat_patch_delta == real_patch_delta;
1549 if (!patch_delta_verified) {
1550 compound_msg += StringPrintf(" Oat image patch delta incorrect (expected 0x%x, recieved 0x%x)",
1551 real_patch_delta, oat_patch_delta);
1552 }
1553 } else {
1554 // If an oat file is PIC, we ignore offset and patching delta.
1555 offset_verified = true;
1556 patch_delta_verified = true;
Alex Lighta59dd802014-07-02 16:28:08 -07001557 }
1558
1559 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
1560 if (ret) {
1561 *error_msg = compound_msg;
1562 }
1563 return ret;
1564}
1565
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001566const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1567 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001568 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001569 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001570 return oat_file;
1571 }
1572
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001573 return OatFile::Open(oat_location, oat_location, nullptr, nullptr, !Runtime::Current()->IsCompiler(),
Andreas Gampe35439ba2014-08-28 14:41:02 -07001574 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001575}
1576
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001577static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
Ian Rogers848871b2013-08-05 10:56:33 -07001578 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001579 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1580
Andreas Gampe35439ba2014-08-28 14:41:02 -07001581 DCHECK(obj != nullptr);
1582 DCHECK(class_linker != nullptr);
Ian Rogers848871b2013-08-05 10:56:33 -07001583
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001584 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001585 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001586 if (!method->IsNative()) {
1587 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
1588 if (method != Runtime::Current()->GetResolutionMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001589 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers63bc11e2014-09-18 08:56:45 -07001590#if defined(ART_USE_PORTABLE_COMPILER)
Ian Rogersef7d42f2014-01-06 12:55:46 -08001591 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers63bc11e2014-09-18 08:56:45 -07001592#endif
Ian Rogers848871b2013-08-05 10:56:33 -07001593 }
1594 }
1595 }
1596}
1597
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001598void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001599 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001600 CHECK(!init_done_);
1601
Mathieu Chartier590fee92013-09-13 13:46:47 -07001602 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001603 gc::Heap* heap = Runtime::Current()->GetHeap();
1604 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001605 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe35439ba2014-08-28 14:41:02 -07001606 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001607 OatFile& oat_file = GetImageOatFile(space);
1608 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1609 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001610 const char* image_file_location = oat_file.GetOatHeader().
1611 GetStoreValueByKey(OatHeader::kImageLocationKey);
1612 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001613 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1614 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001615 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1616 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001617 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001618 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001619 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1620 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1621 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001622
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001623 StackHandleScope<1> hs(self);
1624 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1625 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1626 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001627 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001628
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001629 // Special case of setting up the String class early so that we can test arbitrary objects
1630 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001631 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001632
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001633 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001634 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001635 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001636 StackHandleScope<1> hs(self);
1637 Handle<mirror::DexCache> dex_cache(hs.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001638 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001639 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1640 nullptr);
Andreas Gampe35439ba2014-08-28 14:41:02 -07001641 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001642 std::string error_msg;
1643 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Andreas Gampe35439ba2014-08-28 14:41:02 -07001644 if (dex_file == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001645 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001646 << " from within oat file " << oat_file.GetLocation()
1647 << " error '" << error_msg << "'";
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001648 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001649
1650 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1651
1652 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001653 }
1654
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001655 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1656 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001657 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartiere832e642014-11-10 11:08:06 -08001658 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
1659 if (!Runtime::Current()->IsCompiler()) {
1660 // Compiler supports having an image with a different pointer size than the runtime. This
1661 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
1662 // also use 32 bit dex2oat on a system with 64 bit apps.
1663 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
1664 << sizeof(void*);
1665 }
1666 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
1667 image_pointer_size_ = 4;
1668 } else {
1669 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
1670 image_pointer_size_ = 8;
1671 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001672
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001673 // Set entry point to interpreter if in InterpretOnly mode.
1674 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001675 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001676 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001677 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001678
1679 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001680 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001681 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001682
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001683 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001684 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartiere832e642014-11-10 11:08:06 -08001685 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001686 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001687 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001688 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001689 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1690 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1691 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1692 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1693 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1694 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1695 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1696 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1697 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1698 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001699
Ian Rogers98379392014-02-24 16:53:16 -08001700 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001701
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001702 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001703}
1704
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001705void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1706 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1707 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08001708 for (GcRoot<mirror::Class>& root : class_table_) {
Mathieu Chartier12f74232015-01-14 14:55:47 -08001709 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08001710 }
1711 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
Mathieu Chartier12f74232015-01-14 14:55:47 -08001712 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001713 }
1714 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08001715 for (auto& root : new_class_roots_) {
1716 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartier12f74232015-01-14 14:55:47 -08001717 root.VisitRoot(callback, arg, RootInfo(kRootStickyClass));
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08001718 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001719 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001720 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1721 // corresponding object. This is slow, but luckily for us, this may only happen with a
1722 // concurrent moving GC.
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08001723 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
Mathieu Chartier12f74232015-01-14 14:55:47 -08001724 DCHECK(it != class_table_.end());
1725 *it = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001726 }
1727 }
1728 }
1729 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1730 new_class_roots_.clear();
1731 }
1732 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1733 log_new_class_table_roots_ = true;
1734 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1735 log_new_class_table_roots_ = false;
1736 }
1737 // We deliberately ignore the class roots in the image since we
1738 // handle image roots by using the MS/CMS rescanning of dirty cards.
1739}
1740
Brian Carlstroma663ea52011-08-19 23:33:41 -07001741// Keep in sync with InitCallback. Anything we visit, we need to
1742// reinit references to when reinitializing a ClassLinker from a
1743// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001744void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Mathieu Chartier12f74232015-01-14 14:55:47 -08001745 class_roots_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Ian Rogers50b35e22012-10-04 10:09:15 -07001746 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001747 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001748 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001749 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001750 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
Mathieu Chartier12f74232015-01-14 14:55:47 -08001751 dex_cache.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -07001752 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001753 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1754 for (size_t index : new_dex_cache_roots_) {
Mathieu Chartier12f74232015-01-14 14:55:47 -08001755 dex_caches_[index].VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -07001756 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001757 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001758 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1759 new_dex_cache_roots_.clear();
1760 }
1761 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1762 log_new_dex_caches_roots_ = true;
1763 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1764 log_new_dex_caches_roots_ = false;
1765 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001766 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001767 VisitClassRoots(callback, arg, flags);
Mathieu Chartier12f74232015-01-14 14:55:47 -08001768 array_iftable_.VisitRoot(callback, arg, RootInfo(kRootVMInternal));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001769 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001770 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Mathieu Chartier12f74232015-01-14 14:55:47 -08001771 find_array_class_cache_[i].VisitRootIfNonNull(callback, arg, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -08001772 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001773}
1774
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001775void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1776 if (dex_cache_image_class_lookup_required_) {
1777 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001778 }
Ian Rogersca0c8d32014-08-29 15:40:08 -07001779 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001780 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08001781 for (GcRoot<mirror::Class>& root : class_table_) {
1782 if (!visitor(root.Read(), arg)) {
1783 return;
1784 }
1785 }
1786 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1787 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001788 return;
1789 }
1790 }
1791}
1792
Ian Rogersca0c8d32014-08-29 15:40:08 -07001793static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001794 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001795 classes->insert(c);
1796 return true;
1797}
1798
Ian Rogersca0c8d32014-08-29 15:40:08 -07001799struct GetClassesVisitorArrayArg {
1800 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1801 int32_t index;
1802 bool success;
1803};
1804
1805static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1806 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1807 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1808 if (arg->index < (*arg->classes)->GetLength()) {
1809 (*arg->classes)->Set(arg->index, c);
1810 arg->index++;
1811 return true;
1812 } else {
1813 arg->success = false;
1814 return false;
1815 }
1816}
1817
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001818void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersca0c8d32014-08-29 15:40:08 -07001819 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1820 // is avoiding duplicates.
1821 if (!kMovingClasses) {
1822 std::set<mirror::Class*> classes;
1823 VisitClasses(GetClassesVisitorSet, &classes);
1824 for (mirror::Class* klass : classes) {
1825 if (!visitor(klass, arg)) {
1826 return;
1827 }
1828 }
1829 } else {
1830 Thread* self = Thread::Current();
1831 StackHandleScope<1> hs(self);
1832 Handle<mirror::ObjectArray<mirror::Class>> classes =
1833 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1834 GetClassesVisitorArrayArg local_arg;
1835 local_arg.classes = &classes;
1836 local_arg.success = false;
1837 // We size the array assuming classes won't be added to the class table during the visit.
1838 // If this assumption fails we iterate again.
1839 while (!local_arg.success) {
1840 size_t class_table_size;
1841 {
1842 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08001843 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersca0c8d32014-08-29 15:40:08 -07001844 }
1845 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1846 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1847 classes.Assign(
1848 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1849 CHECK(classes.Get() != nullptr); // OOME.
1850 local_arg.index = 0;
1851 local_arg.success = true;
1852 VisitClasses(GetClassesVisitorArray, &local_arg);
1853 }
1854 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1855 // If the class table shrank during creation of the clases array we expect null elements. If
1856 // the class table grew then the loop repeats. If classes are created after the loop has
1857 // finished then we don't visit.
1858 mirror::Class* klass = classes->Get(i);
1859 if (klass != nullptr && !visitor(klass, arg)) {
1860 return;
1861 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001862 }
1863 }
1864}
1865
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001866ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001867 mirror::Class::ResetClass();
1868 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001869 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001870 mirror::ArtField::ResetClass();
1871 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001872 mirror::BooleanArray::ResetArrayClass();
1873 mirror::ByteArray::ResetArrayClass();
1874 mirror::CharArray::ResetArrayClass();
1875 mirror::DoubleArray::ResetArrayClass();
1876 mirror::FloatArray::ResetArrayClass();
1877 mirror::IntArray::ResetArrayClass();
1878 mirror::LongArray::ResetArrayClass();
1879 mirror::ShortArray::ResetArrayClass();
1880 mirror::Throwable::ResetClass();
1881 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001882 STLDeleteElements(&boot_class_path_);
1883 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001884}
1885
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001886mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001887 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001888 StackHandleScope<16> hs(self);
1889 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1890 Handle<mirror::DexCache> dex_cache(
1891 hs.NewHandle(down_cast<mirror::DexCache*>(
1892 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1893 VoidFunctor()))));
Andreas Gampe35439ba2014-08-28 14:41:02 -07001894 if (dex_cache.Get() == nullptr) {
1895 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001896 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001897 Handle<mirror::String>
1898 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe35439ba2014-08-28 14:41:02 -07001899 if (location.Get() == nullptr) {
1900 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001901 }
Ian Rogers700a4022014-05-19 16:49:03 -07001902 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001903 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe35439ba2014-08-28 14:41:02 -07001904 if (strings.Get() == nullptr) {
1905 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001906 }
Ian Rogers700a4022014-05-19 16:49:03 -07001907 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001908 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe35439ba2014-08-28 14:41:02 -07001909 if (types.Get() == nullptr) {
1910 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001911 }
Ian Rogers700a4022014-05-19 16:49:03 -07001912 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001913 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe35439ba2014-08-28 14:41:02 -07001914 if (methods.Get() == nullptr) {
1915 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001916 }
Ian Rogers700a4022014-05-19 16:49:03 -07001917 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001918 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe35439ba2014-08-28 14:41:02 -07001919 if (fields.Get() == nullptr) {
1920 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001921 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001922 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1923 fields.Get());
1924 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001925}
1926
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001927mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001928 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001929 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001930 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001931 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001932 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001933 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1934 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001935 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001936 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001937 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001938 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001939 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001940}
1941
Ian Rogers6fac4472014-02-25 17:01:10 -08001942mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001943 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001944}
1945
Brian Carlstromea46f952013-07-30 01:26:50 -07001946mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001947 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001948 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001949}
1950
Brian Carlstromea46f952013-07-30 01:26:50 -07001951mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001952 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001953 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001954}
1955
Mathieu Chartier590fee92013-09-13 13:46:47 -07001956mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1957 Thread* self, size_t length) {
1958 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1959 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001960}
1961
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001962mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1963 mirror::Class* klass) {
Andreas Gampe35439ba2014-08-28 14:41:02 -07001964 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001965
1966 // For temporary classes we must wait for them to be retired.
1967 if (init_done_ && klass->IsTemp()) {
1968 CHECK(!klass->IsResolved());
1969 if (klass->IsErroneous()) {
1970 ThrowEarlierClassFailure(klass);
1971 return nullptr;
1972 }
1973 StackHandleScope<1> hs(self);
1974 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1975 ObjectLock<mirror::Class> lock(self, h_class);
1976 // Loop and wait for the resolving thread to retire this class.
1977 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1978 lock.WaitIgnoringInterrupts();
1979 }
1980 if (h_class->IsErroneous()) {
1981 ThrowEarlierClassFailure(h_class.Get());
1982 return nullptr;
1983 }
1984 CHECK(h_class->IsRetired());
1985 // Get the updated class from class table.
Mathieu Chartier564ff982014-11-06 16:35:45 -08001986 klass = LookupClass(descriptor, ComputeModifiedUtf8Hash(descriptor),
1987 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001988 }
1989
Brian Carlstromaded5f72011-10-07 17:15:04 -07001990 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001991 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001992 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001993 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
1994 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001995 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001996 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
1997 ThrowClassCircularityError(h_class.Get());
1998 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001999 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002000 }
2001 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002002 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002003 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002004 }
2005 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002006
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002007 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002008 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002009 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002010 }
2011 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002012 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002013 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002014 return klass;
2015}
2016
Ian Rogerscc2f2392014-08-29 20:19:11 -07002017typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2018
2019// Search a collection of DexFiles for a descriptor
2020ClassPathEntry FindInClassPath(const char* descriptor,
Mathieu Chartier564ff982014-11-06 16:35:45 -08002021 size_t hash, const std::vector<const DexFile*>& class_path) {
2022 for (const DexFile* dex_file : class_path) {
2023 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe35439ba2014-08-28 14:41:02 -07002024 if (dex_class_def != nullptr) {
Ian Rogerscc2f2392014-08-29 20:19:11 -07002025 return ClassPathEntry(dex_file, dex_class_def);
2026 }
2027 }
Mathieu Chartier564ff982014-11-06 16:35:45 -08002028 return ClassPathEntry(nullptr, nullptr);
Ian Rogerscc2f2392014-08-29 20:19:11 -07002029}
2030
Mathieu Chartier194116c2014-09-11 14:21:41 -07002031mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2032 Thread* self, const char* descriptor,
Mathieu Chartier564ff982014-11-06 16:35:45 -08002033 size_t hash,
Mathieu Chartier194116c2014-09-11 14:21:41 -07002034 Handle<mirror::ClassLoader> class_loader) {
2035 if (class_loader->GetClass() !=
2036 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2037 class_loader->GetParent()->GetClass() !=
2038 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2039 return nullptr;
2040 }
Mathieu Chartier564ff982014-11-06 16:35:45 -08002041 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartier194116c2014-09-11 14:21:41 -07002042 // Check if this would be found in the parent boot class loader.
2043 if (pair.second != nullptr) {
Mathieu Chartier564ff982014-11-06 16:35:45 -08002044 mirror::Class* klass = LookupClass(descriptor, hash, nullptr);
Mathieu Chartier194116c2014-09-11 14:21:41 -07002045 if (klass != nullptr) {
2046 return EnsureResolved(self, descriptor, klass);
2047 }
Mathieu Chartier564ff982014-11-06 16:35:45 -08002048 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Mathieu Chartier194116c2014-09-11 14:21:41 -07002049 *pair.second);
2050 if (klass != nullptr) {
2051 return klass;
2052 }
2053 CHECK(self->IsExceptionPending()) << descriptor;
2054 self->ClearException();
2055 } else {
2056 // RegisterDexFile may allocate dex caches (and cause thread suspension).
2057 StackHandleScope<3> hs(self);
2058 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2059 // We need to get the DexPathList and loop through it.
2060 Handle<mirror::ArtField> cookie_field =
2061 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2062 Handle<mirror::ArtField> dex_file_field =
2063 hs.NewHandle(
2064 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList$Element_dexFile));
2065 mirror::Object* dex_path_list =
2066 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2067 GetObject(class_loader.Get());
2068 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2069 cookie_field.Get() != nullptr) {
2070 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2071 mirror::Object* dex_elements_obj =
2072 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2073 GetObject(dex_path_list);
2074 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2075 // at the mCookie which is a DexFile vector.
2076 if (dex_elements_obj != nullptr) {
2077 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2078 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2079 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2080 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2081 if (element == nullptr) {
2082 // Should never happen, fall back to java code to throw a NPE.
2083 break;
2084 }
2085 mirror::Object* dex_file = dex_file_field->GetObject(element);
2086 if (dex_file != nullptr) {
2087 const uint64_t cookie = cookie_field->GetLong(dex_file);
2088 auto* dex_files =
2089 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2090 if (dex_files == nullptr) {
2091 // This should never happen so log a warning.
2092 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2093 break;
2094 }
2095 for (const DexFile* dex_file : *dex_files) {
Mathieu Chartier564ff982014-11-06 16:35:45 -08002096 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Mathieu Chartier194116c2014-09-11 14:21:41 -07002097 if (dex_class_def != nullptr) {
2098 RegisterDexFile(*dex_file);
Mathieu Chartier564ff982014-11-06 16:35:45 -08002099 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader, *dex_file,
2100 *dex_class_def);
Mathieu Chartier194116c2014-09-11 14:21:41 -07002101 if (klass == nullptr) {
2102 CHECK(self->IsExceptionPending()) << descriptor;
2103 self->ClearException();
2104 return nullptr;
2105 }
2106 return klass;
2107 }
2108 }
2109 }
2110 }
2111 }
2112 }
2113 }
2114 return nullptr;
2115}
2116
Ian Rogers98379392014-02-24 16:53:16 -08002117mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002118 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002119 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002120 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002121 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002122 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002123 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2124 // for primitive classes that aren't backed by dex files.
2125 return FindPrimitiveClass(descriptor[0]);
2126 }
Mathieu Chartier564ff982014-11-06 16:35:45 -08002127 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002128 // Find the class in the loaded classes table.
Mathieu Chartier564ff982014-11-06 16:35:45 -08002129 mirror::Class* klass = LookupClass(descriptor, hash, class_loader.Get());
Ian Rogerscc2f2392014-08-29 20:19:11 -07002130 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002131 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002132 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002133 // Class is not yet loaded.
2134 if (descriptor[0] == '[') {
Mathieu Chartier564ff982014-11-06 16:35:45 -08002135 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002136 } else if (class_loader.Get() == nullptr) {
Ian Rogers79cfc0e2014-06-04 16:57:15 -07002137 // The boot class loader, search the boot class path.
Mathieu Chartier564ff982014-11-06 16:35:45 -08002138 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogerscc2f2392014-08-29 20:19:11 -07002139 if (pair.second != nullptr) {
Mathieu Chartier564ff982014-11-06 16:35:45 -08002140 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
2141 *pair.second);
Ian Rogers79cfc0e2014-06-04 16:57:15 -07002142 } else {
2143 // The boot class loader is searched ahead of the application class loader, failures are
2144 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2145 // trigger the chaining with a proper stack trace.
2146 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2147 self->SetException(ThrowLocation(), pre_allocated);
2148 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002149 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002150 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogerscc2f2392014-08-29 20:19:11 -07002151 // First try with the bootstrap class loader.
2152 if (class_loader.Get() != nullptr) {
Mathieu Chartier564ff982014-11-06 16:35:45 -08002153 klass = LookupClass(descriptor, hash, nullptr);
Ian Rogerscc2f2392014-08-29 20:19:11 -07002154 if (klass != nullptr) {
2155 return EnsureResolved(self, descriptor, klass);
2156 }
2157 }
Ian Rogers79cfc0e2014-06-04 16:57:15 -07002158 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2159 // a NoClassDefFoundError being allocated.
Mathieu Chartier564ff982014-11-06 16:35:45 -08002160 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogerscc2f2392014-08-29 20:19:11 -07002161 if (pair.second != nullptr) {
Mathieu Chartier564ff982014-11-06 16:35:45 -08002162 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
2163 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002164 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002165 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002166 const std::vector<const DexFile*>* class_path;
2167 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002168 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002169 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002170 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002171 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2172 }
Mathieu Chartier564ff982014-11-06 16:35:45 -08002173 pair = FindInClassPath(descriptor, hash, *class_path);
Ian Rogerscc2f2392014-08-29 20:19:11 -07002174 if (pair.second != nullptr) {
Mathieu Chartier564ff982014-11-06 16:35:45 -08002175 return DefineClass(self, descriptor, hash, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002176 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002177 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002178 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier564ff982014-11-06 16:35:45 -08002179 mirror::Class* klass = FindClassInPathClassLoader(soa, self, descriptor, hash, class_loader);
Mathieu Chartier194116c2014-09-11 14:21:41 -07002180 if (klass != nullptr) {
2181 return klass;
Mathieu Chartier8a39e7f2014-09-04 18:33:17 -07002182 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002183 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002184 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002185 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogerscc2f2392014-08-29 20:19:11 -07002186 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002187 {
2188 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002189 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2190 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogerscc2f2392014-08-29 20:19:11 -07002191 if (class_name_object.get() == nullptr) {
Ian Rogers79cfc0e2014-06-04 16:57:15 -07002192 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogerscc2f2392014-08-29 20:19:11 -07002193 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002194 }
Ian Rogerscc2f2392014-08-29 20:19:11 -07002195 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002196 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2197 WellKnownClasses::java_lang_ClassLoader_loadClass,
2198 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002199 }
Ian Rogers98379392014-02-24 16:53:16 -08002200 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002201 // If the ClassLoader threw, pass that exception up.
Ian Rogerscc2f2392014-08-29 20:19:11 -07002202 return nullptr;
2203 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002204 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogerscc2f2392014-08-29 20:19:11 -07002205 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers79cfc0e2014-06-04 16:57:15 -07002206 class_name_string.c_str()).c_str());
Ian Rogerscc2f2392014-08-29 20:19:11 -07002207 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002208 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002209 // success, return mirror::Class*
2210 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002211 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002212 }
2213
Elliott Hughes82914b62012-04-09 15:56:29 -07002214 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
Ian Rogerscc2f2392014-08-29 20:19:11 -07002215 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002216}
2217
Mathieu Chartier564ff982014-11-06 16:35:45 -08002218mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002219 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002220 const DexFile& dex_file,
2221 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002222 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002223 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002224
Brian Carlstromaded5f72011-10-07 17:15:04 -07002225 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002226 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002227 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002228 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002229 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002230 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002231 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002232 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002233 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002234 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2235 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002236 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002237 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002238 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002239 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002240 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002241 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002242 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002243 }
2244
Mathieu Chartier564ff982014-11-06 16:35:45 -08002245 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002246 // Allocate a class with the status of not ready.
2247 // Interface object should get the right size here. Regular class will
2248 // figure out the right size later and be replaced with one of the right
2249 // size when the class becomes resolved.
2250 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002251 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002252 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002253 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002254 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002255 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002256 klass->SetDexCache(FindDexCache(dex_file));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002257 LoadClass(dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002258 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002259 if (self->IsExceptionPending()) {
2260 // An exception occured during load, set status to erroneous while holding klass' lock in case
2261 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002262 if (!klass->IsErroneous()) {
2263 klass->SetStatus(mirror::Class::kStatusError, self);
2264 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002265 return nullptr;
2266 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002267 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002268
Mathieu Chartier590fee92013-09-13 13:46:47 -07002269 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier564ff982014-11-06 16:35:45 -08002270 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002271 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002272 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2273 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002274 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002275 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002276
Brian Carlstromaded5f72011-10-07 17:15:04 -07002277 // Finish loading (if necessary) by finding parents
2278 CHECK(!klass->IsLoaded());
2279 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2280 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002281 if (!klass->IsErroneous()) {
2282 klass->SetStatus(mirror::Class::kStatusError, self);
2283 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002284 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002285 }
2286 CHECK(klass->IsLoaded());
2287 // Link the class (if necessary)
2288 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002289 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002290 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002291
2292 mirror::Class* new_class = nullptr;
2293 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002294 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002295 if (!klass->IsErroneous()) {
2296 klass->SetStatus(mirror::Class::kStatusError, self);
2297 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002298 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002299 }
Mathieu Chartier58c016c2014-08-27 15:28:28 -07002300 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002301 CHECK(new_class != nullptr) << descriptor;
2302 CHECK(new_class->IsResolved()) << descriptor;
2303
2304 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002305
2306 /*
2307 * We send CLASS_PREPARE events to the debugger from here. The
2308 * definition of "preparation" is creating the static fields for a
2309 * class and initializing them to the standard default values, but not
2310 * executing any code (that comes later, during "initialization").
2311 *
2312 * We did the static preparation in LinkClass.
2313 *
2314 * The class has been prepared and resolved but possibly not yet verified
2315 * at this point.
2316 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002317 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002318
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002319 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002320}
2321
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002322uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2323 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002324 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002325 size_t num_ref = 0;
2326 size_t num_32 = 0;
2327 size_t num_64 = 0;
Andreas Gampe35439ba2014-08-28 14:41:02 -07002328 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002329 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2330 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002331 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002332 char c = descriptor[0];
2333 if (c == 'L' || c == '[') {
2334 num_ref++;
2335 } else if (c == 'J' || c == 'D') {
2336 num_64++;
2337 } else {
2338 num_32++;
2339 }
2340 }
2341 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002342 return mirror::Class::ComputeClassSize(false, 0, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002343}
2344
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002345bool ClassLinker::FindOatClass(const DexFile& dex_file,
2346 uint16_t class_def_idx,
2347 OatFile::OatClass* oat_class) {
2348 DCHECK(oat_class != nullptr);
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002349 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markobe4e6432014-09-05 14:01:17 +01002350 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2351 if (oat_dex_file == nullptr) {
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002352 return false;
2353 }
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002354 *oat_class = oat_dex_file->GetOatClass(class_def_idx);
2355 return true;
Ian Rogers19846512012-02-24 11:42:47 -08002356}
2357
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002358static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2359 uint32_t method_idx) {
2360 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
2361 const byte* class_data = dex_file.GetClassData(class_def);
Andreas Gampe35439ba2014-08-28 14:41:02 -07002362 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002363 ClassDataItemIterator it(dex_file, class_data);
2364 // Skip fields
2365 while (it.HasNextStaticField()) {
2366 it.Next();
2367 }
2368 while (it.HasNextInstanceField()) {
2369 it.Next();
2370 }
2371 // Process methods
2372 size_t class_def_method_index = 0;
2373 while (it.HasNextDirectMethod()) {
2374 if (it.GetMemberIndex() == method_idx) {
2375 return class_def_method_index;
2376 }
2377 class_def_method_index++;
2378 it.Next();
2379 }
2380 while (it.HasNextVirtualMethod()) {
2381 if (it.GetMemberIndex() == method_idx) {
2382 return class_def_method_index;
2383 }
2384 class_def_method_index++;
2385 it.Next();
2386 }
2387 DCHECK(!it.HasNext());
2388 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2389 return 0;
2390}
2391
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002392bool ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, OatFile::OatMethod* oat_method) {
2393 DCHECK(oat_method != nullptr);
Ian Rogers19846512012-02-24 11:42:47 -08002394 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002395 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002396 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002397 size_t oat_method_index;
2398 if (method->IsStatic() || method->IsDirect()) {
2399 // Simple case where the oat method index was stashed at load time.
2400 oat_method_index = method->GetMethodIndex();
2401 } else {
2402 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2403 // by search for its position in the declared virtual methods.
2404 oat_method_index = declaring_class->NumDirectMethods();
2405 size_t end = declaring_class->NumVirtualMethods();
2406 bool found = false;
2407 for (size_t i = 0; i < end; i++) {
Jeff Hao6b28a452014-09-03 13:48:16 -07002408 // Check method index instead of identity in case of duplicate method definitions.
2409 if (method->GetDexMethodIndex() ==
2410 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08002411 found = true;
2412 break;
2413 }
Ian Rogersf320b632012-03-13 18:47:47 -07002414 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002415 }
2416 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method);
2417 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002418 DCHECK_EQ(oat_method_index,
2419 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002420 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002421 method->GetDexMethodIndex()));
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002422 OatFile::OatClass oat_class;
2423 if (!FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2424 declaring_class->GetDexClassDefIndex(),
2425 &oat_class)) {
2426 return false;
2427 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002428
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002429 *oat_method = oat_class.GetOatMethod(oat_method_index);
2430 return true;
TDYa12785321912012-04-01 15:24:56 -07002431}
2432
2433// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002434const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002435 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002436 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002437 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002438 }
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002439 OatFile::OatMethod oat_method;
2440 const void* result = nullptr;
2441 if (FindOatMethodFor(method, &oat_method)) {
2442 result = oat_method.GetQuickCode();
2443 }
2444
Ian Rogersef7d42f2014-01-06 12:55:46 -08002445 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002446 if (method->IsNative()) {
2447 // No code and native? Use generic trampoline.
2448 result = GetQuickGenericJniTrampoline();
Ian Rogers63bc11e2014-09-18 08:56:45 -07002449#if defined(ART_USE_PORTABLE_COMPILER)
Ian Rogers1a570662014-03-12 01:02:21 -07002450 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002451 // No code? Do we expect portable code?
2452 result = GetQuickToPortableBridge();
Ian Rogers63bc11e2014-09-18 08:56:45 -07002453#endif
Ian Rogersef7d42f2014-01-06 12:55:46 -08002454 } else {
2455 // No code? You must mean to go into the interpreter.
2456 result = GetQuickToInterpreterBridge();
2457 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002458 }
2459 return result;
TDYa12785321912012-04-01 15:24:56 -07002460}
2461
Ian Rogers63bc11e2014-09-18 08:56:45 -07002462#if defined(ART_USE_PORTABLE_COMPILER)
Ian Rogersef7d42f2014-01-06 12:55:46 -08002463const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2464 bool* have_portable_code) {
2465 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2466 *have_portable_code = false;
2467 if (method->IsProxyMethod()) {
2468 return GetPortableProxyInvokeHandler();
2469 }
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002470 OatFile::OatMethod oat_method;
2471 const void* result = nullptr;
2472 const void* quick_code = nullptr;
2473 if (FindOatMethodFor(method, &oat_method)) {
2474 result = oat_method.GetPortableCode();
2475 quick_code = oat_method.GetQuickCode();
2476 }
2477
Ian Rogersef7d42f2014-01-06 12:55:46 -08002478 if (result == nullptr) {
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002479 if (quick_code == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002480 // No code? You must mean to go into the interpreter.
2481 result = GetPortableToInterpreterBridge();
2482 } else {
2483 // No code? But there's quick code, so use a bridge.
2484 result = GetPortableToQuickBridge();
2485 }
2486 } else {
2487 *have_portable_code = true;
2488 }
2489 return result;
2490}
Ian Rogers63bc11e2014-09-18 08:56:45 -07002491#endif
Ian Rogersef7d42f2014-01-06 12:55:46 -08002492
Sebastien Hertzf2134f62014-11-17 19:00:37 +01002493const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2494 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2495 return nullptr;
2496 }
2497 OatFile::OatMethod oat_method;
2498 bool found = FindOatMethodFor(method, &oat_method);
2499 return found ? oat_method.GetQuickCode() : nullptr;
2500}
2501
Ian Rogersef7d42f2014-01-06 12:55:46 -08002502const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2503 uint32_t method_idx) {
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002504 OatFile::OatClass oat_class;
2505 if (!FindOatClass(dex_file, class_def_idx, &oat_class)) {
2506 return nullptr;
2507 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002508 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002509 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002510}
2511
Ian Rogers63bc11e2014-09-18 08:56:45 -07002512#if defined(ART_USE_PORTABLE_COMPILER)
Ian Rogersef7d42f2014-01-06 12:55:46 -08002513const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2514 uint32_t method_idx) {
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002515 OatFile::OatClass oat_class;
2516 if (!FindOatClass(dex_file, class_def_idx, &oat_class)) {
2517 return nullptr;
2518 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002519 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002520 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002521}
Ian Rogers63bc11e2014-09-18 08:56:45 -07002522#endif
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002523
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002524// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002525static bool NeedsInterpreter(
2526 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2527 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002528 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002529 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002530 // May return true for native code, in the case of generic JNI
2531 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002532 return true;
2533 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002534#ifdef ART_SEA_IR_MODE
2535 ScopedObjectAccess soa(Thread::Current());
2536 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2537 LOG(INFO) << "Found " << PrettyMethod(method);
2538 return false;
2539 }
2540#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002541 // If interpreter mode is enabled, every method (except native and proxy) must
2542 // be run with interpreter.
2543 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2544 !method->IsNative() && !method->IsProxyMethod();
2545}
2546
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002547void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002548 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002549 if (klass->NumDirectMethods() == 0) {
2550 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002551 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002552 Runtime* runtime = Runtime::Current();
2553 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light507e6182014-08-19 14:23:13 -07002554 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2555 return; // OAT file unavailable.
2556 }
Ian Rogers19846512012-02-24 11:42:47 -08002557 }
Alex Light507e6182014-08-19 14:23:13 -07002558
Mathieu Chartierf8322842014-05-16 10:59:25 -07002559 const DexFile& dex_file = klass->GetDexFile();
2560 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002561 CHECK(dex_class_def != nullptr);
2562 const byte* class_data = dex_file.GetClassData(*dex_class_def);
2563 // There should always be class data if there were direct methods.
2564 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002565 ClassDataItemIterator it(dex_file, class_data);
2566 // Skip fields
2567 while (it.HasNextStaticField()) {
2568 it.Next();
2569 }
2570 while (it.HasNextInstanceField()) {
2571 it.Next();
2572 }
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002573 OatFile::OatClass oat_class;
2574 bool has_oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(), &oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002575 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002576 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002577 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002578 if (!method->IsStatic()) {
2579 // Only update static methods.
2580 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002581 }
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002582 const void* portable_code = nullptr;
2583 const void* quick_code = nullptr;
2584 if (has_oat_class) {
2585 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2586 portable_code = oat_method.GetPortableCode();
2587 quick_code = oat_method.GetQuickCode();
2588 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002589 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2590 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002591 if (enter_interpreter) {
2592 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002593 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002594 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
2595 quick_code = GetQuickGenericJniTrampoline();
Ian Rogers63bc11e2014-09-18 08:56:45 -07002596#if defined(ART_USE_PORTABLE_COMPILER)
Ian Rogers1a570662014-03-12 01:02:21 -07002597 portable_code = GetPortableToQuickBridge();
Ian Rogers63bc11e2014-09-18 08:56:45 -07002598#endif
Andreas Gampe2da88232014-02-27 12:26:20 -08002599 } else {
Ian Rogers63bc11e2014-09-18 08:56:45 -07002600#if defined(ART_USE_PORTABLE_COMPILER)
Ian Rogers1a570662014-03-12 01:02:21 -07002601 portable_code = GetPortableToInterpreterBridge();
Ian Rogers63bc11e2014-09-18 08:56:45 -07002602#endif
Andreas Gampe2da88232014-02-27 12:26:20 -08002603 quick_code = GetQuickToInterpreterBridge();
2604 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002605 } else {
Ian Rogers63bc11e2014-09-18 08:56:45 -07002606#if defined(ART_USE_PORTABLE_COMPILER)
Ian Rogersef7d42f2014-01-06 12:55:46 -08002607 if (portable_code == nullptr) {
2608 portable_code = GetPortableToQuickBridge();
2609 } else {
2610 have_portable_code = true;
2611 }
2612 if (quick_code == nullptr) {
2613 quick_code = GetQuickToPortableBridge();
2614 }
Ian Rogers63bc11e2014-09-18 08:56:45 -07002615#else
2616 if (quick_code == nullptr) {
2617 quick_code = GetQuickToInterpreterBridge();
2618 }
2619#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002620 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002621 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2622 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002623 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002624 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002625}
2626
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002627void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method, const OatFile::OatClass* oat_class,
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002628 const DexFile& dex_file, uint32_t dex_method_index,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002629 uint32_t method_index) {
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002630 if (Runtime::Current()->IsCompiler()) {
2631 // The following code only applies to a non-compiler runtime.
2632 return;
2633 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002634 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002635 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Ian Rogers63bc11e2014-09-18 08:56:45 -07002636#if defined(ART_USE_PORTABLE_COMPILER)
Ian Rogersef7d42f2014-01-06 12:55:46 -08002637 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Ian Rogers63bc11e2014-09-18 08:56:45 -07002638#endif
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002639 if (oat_class != nullptr) {
2640 // Every kind of method should at least get an invoke stub from the oat_method.
2641 // non-abstract methods also get their code pointers.
2642 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
2643 oat_method.LinkMethod(method.Get());
2644 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002645
Jeff Hao16743632013-05-08 10:59:04 -07002646 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002647 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002648 method->GetEntryPointFromQuickCompiledCode(),
Ian Rogers63bc11e2014-09-18 08:56:45 -07002649#if defined(ART_USE_PORTABLE_COMPILER)
Ian Rogersef7d42f2014-01-06 12:55:46 -08002650 method->GetEntryPointFromPortableCompiledCode());
Ian Rogers63bc11e2014-09-18 08:56:45 -07002651#else
2652 nullptr);
2653#endif
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002654 if (enter_interpreter && !method->IsNative()) {
Ian Rogers848871b2013-08-05 10:56:33 -07002655 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002656 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002657 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002658 }
2659
Brian Carlstrom92827a52011-10-10 15:50:01 -07002660 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002661 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers63bc11e2014-09-18 08:56:45 -07002662#if defined(ART_USE_PORTABLE_COMPILER)
Ian Rogersef7d42f2014-01-06 12:55:46 -08002663 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers63bc11e2014-09-18 08:56:45 -07002664#endif
Brian Carlstrom92827a52011-10-10 15:50:01 -07002665 return;
2666 }
Ian Rogers19846512012-02-24 11:42:47 -08002667
Ian Rogersef7d42f2014-01-06 12:55:46 -08002668 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002669 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002670 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002671 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2672 // after initializing class (see ClassLinker::InitializeClass method).
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002673 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionTrampoline());
Ian Rogers63bc11e2014-09-18 08:56:45 -07002674#if defined(ART_USE_PORTABLE_COMPILER)
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002675 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionTrampoline());
Ian Rogers63bc11e2014-09-18 08:56:45 -07002676#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002677 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002678 if (!method->IsNative()) {
2679 // Set entry point from compiled code if there's no code or in interpreter only mode.
2680 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers63bc11e2014-09-18 08:56:45 -07002681#if defined(ART_USE_PORTABLE_COMPILER)
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002682 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers63bc11e2014-09-18 08:56:45 -07002683#endif
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002684 } else {
2685 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniTrampoline());
Ian Rogers63bc11e2014-09-18 08:56:45 -07002686#if defined(ART_USE_PORTABLE_COMPILER)
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002687 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers63bc11e2014-09-18 08:56:45 -07002688#endif
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002689 }
Ian Rogers63bc11e2014-09-18 08:56:45 -07002690#if defined(ART_USE_PORTABLE_COMPILER)
Ian Rogersef7d42f2014-01-06 12:55:46 -08002691 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2692 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2693 have_portable_code = true;
2694 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
Ian Rogers63bc11e2014-09-18 08:56:45 -07002695#endif
Ian Rogersef7d42f2014-01-06 12:55:46 -08002696 } else {
2697 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
Ian Rogers63bc11e2014-09-18 08:56:45 -07002698#if defined(ART_USE_PORTABLE_COMPILER)
Ian Rogersef7d42f2014-01-06 12:55:46 -08002699 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers63bc11e2014-09-18 08:56:45 -07002700#endif
Ian Rogers0d6de042012-02-29 08:50:26 -08002701 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002702
Ian Rogers62d6c772013-02-27 08:32:07 -08002703 if (method->IsNative()) {
2704 // Unregistering restores the dlsym lookup stub.
2705 method->UnregisterNative(Thread::Current());
Andreas Gampe90546832014-03-12 18:07:19 -07002706
2707 if (enter_interpreter) {
2708 // We have a native method here without code. Then it should have either the GenericJni
2709 // trampoline as entrypoint (non-static), or the Resolution trampoline (static).
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002710 DCHECK(method->GetEntryPointFromQuickCompiledCode() == GetQuickResolutionTrampoline()
Andreas Gampe9a6a99a2014-03-14 07:52:20 -07002711 || method->GetEntryPointFromQuickCompiledCode() == GetQuickGenericJniTrampoline());
Andreas Gampe90546832014-03-12 18:07:19 -07002712 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002713 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002714
Ian Rogers62d6c772013-02-27 08:32:07 -08002715 // Allow instrumentation its chance to hijack code.
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002716 Runtime* runtime = Runtime::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002717 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002718 method->GetEntryPointFromQuickCompiledCode(),
Ian Rogers63bc11e2014-09-18 08:56:45 -07002719#if defined(ART_USE_PORTABLE_COMPILER)
Ian Rogersef7d42f2014-01-06 12:55:46 -08002720 method->GetEntryPointFromPortableCompiledCode(),
Ian Rogers63bc11e2014-09-18 08:56:45 -07002721#else
2722 nullptr,
2723#endif
Ian Rogersef7d42f2014-01-06 12:55:46 -08002724 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002725}
2726
Brian Carlstromf615a612011-07-23 12:50:34 -07002727void ClassLinker::LoadClass(const DexFile& dex_file,
2728 const DexFile::ClassDef& dex_class_def,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002729 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002730 mirror::ClassLoader* class_loader) {
Andreas Gampe35439ba2014-08-28 14:41:02 -07002731 CHECK(klass.Get() != nullptr);
2732 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002733 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002734 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe35439ba2014-08-28 14:41:02 -07002735 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002736
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002737 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002738 if (kUseBakerOrBrooksReadBarrier) {
2739 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002740 }
Andreas Gampe7fc8f902014-08-25 15:05:04 -07002741 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002742 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002743 klass->SetAccessFlags(access_flags);
2744 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002745 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe35439ba2014-08-28 14:41:02 -07002746 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002747
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002748 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002749 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierea1c3d72014-12-01 10:31:15 -08002750 CHECK(klass->GetDexCacheStrings() != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002751
Ian Rogers0571d352011-11-03 19:51:38 -07002752 const byte* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe35439ba2014-08-28 14:41:02 -07002753 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002754 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002755 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002756
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002757 OatFile::OatClass oat_class;
2758 if (Runtime::Current()->IsStarted()
2759 && !Runtime::Current()->UseCompileTimeClassPath()
2760 && FindOatClass(dex_file, klass->GetDexClassDefIndex(), &oat_class)) {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002761 LoadClassMembers(dex_file, class_data, klass, class_loader, &oat_class);
2762 } else {
2763 LoadClassMembers(dex_file, class_data, klass, class_loader, nullptr);
2764 }
2765}
2766
2767void ClassLinker::LoadClassMembers(const DexFile& dex_file,
2768 const byte* class_data,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002769 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002770 mirror::ClassLoader* class_loader,
2771 const OatFile::OatClass* oat_class) {
2772 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002773 ClassDataItemIterator it(dex_file, class_data);
Ian Rogers50b35e22012-10-04 10:09:15 -07002774 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07002775 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002776 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe35439ba2014-08-28 14:41:02 -07002777 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002778 CHECK(self->IsExceptionPending()); // OOME.
2779 return;
2780 }
2781 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002782 }
2783 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002784 mirror::ObjectArray<mirror::ArtField>* fields =
2785 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe35439ba2014-08-28 14:41:02 -07002786 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002787 CHECK(self->IsExceptionPending()); // OOME.
2788 return;
2789 }
2790 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002791 }
2792 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002793 StackHandleScope<1> hs(self);
2794 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe35439ba2014-08-28 14:41:02 -07002795 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002796 CHECK(self->IsExceptionPending()); // OOME.
2797 return;
2798 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002799 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002800 LoadField(dex_file, it, klass, sfield);
2801 }
2802 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002803 StackHandleScope<1> hs(self);
2804 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe35439ba2014-08-28 14:41:02 -07002805 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002806 CHECK(self->IsExceptionPending()); // OOME.
2807 return;
2808 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002809 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002810 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002811 }
2812
Ian Rogers0571d352011-11-03 19:51:38 -07002813 // Load methods.
2814 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002815 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002816 mirror::ObjectArray<mirror::ArtMethod>* directs =
2817 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe35439ba2014-08-28 14:41:02 -07002818 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002819 CHECK(self->IsExceptionPending()); // OOME.
2820 return;
2821 }
2822 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002823 }
Ian Rogers0571d352011-11-03 19:51:38 -07002824 if (it.NumVirtualMethods() != 0) {
2825 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002826 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2827 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe35439ba2014-08-28 14:41:02 -07002828 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002829 CHECK(self->IsExceptionPending()); // OOME.
2830 return;
2831 }
2832 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002833 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002834 size_t class_def_method_index = 0;
Jeff Hao6b28a452014-09-03 13:48:16 -07002835 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2836 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002837 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002838 StackHandleScope<1> hs(self);
2839 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe35439ba2014-08-28 14:41:02 -07002840 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002841 CHECK(self->IsExceptionPending()); // OOME.
2842 return;
2843 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002844 klass->SetDirectMethod(i, method.Get());
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002845 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Jeff Hao6b28a452014-09-03 13:48:16 -07002846 uint32_t it_method_index = it.GetMemberIndex();
2847 if (last_dex_method_index == it_method_index) {
2848 // duplicate case
2849 method->SetMethodIndex(last_class_def_method_index);
2850 } else {
2851 method->SetMethodIndex(class_def_method_index);
2852 last_dex_method_index = it_method_index;
2853 last_class_def_method_index = class_def_method_index;
2854 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002855 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002856 }
2857 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002858 StackHandleScope<1> hs(self);
2859 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe35439ba2014-08-28 14:41:02 -07002860 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002861 CHECK(self->IsExceptionPending()); // OOME.
2862 return;
2863 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002864 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002865 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Nicolas Geoffray9c290012014-07-22 10:48:00 +01002866 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002867 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002868 }
2869 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002870}
2871
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002872void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002873 Handle<mirror::Class> klass, Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002874 uint32_t field_idx = it.GetMemberIndex();
2875 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002876 dst->SetDeclaringClass(klass.Get());
Andreas Gampe7fc8f902014-08-25 15:05:04 -07002877 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002878}
2879
Brian Carlstromea46f952013-07-30 01:26:50 -07002880mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002881 const ClassDataItemIterator& it,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002882 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002883 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002884 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002885 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002886
Brian Carlstromea46f952013-07-30 01:26:50 -07002887 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe35439ba2014-08-28 14:41:02 -07002888 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002889 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe35439ba2014-08-28 14:41:02 -07002890 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002891 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002892 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002893
Ian Rogers50b35e22012-10-04 10:09:15 -07002894 const char* old_cause = self->StartAssertNoThreadSuspension("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002895 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002896 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002897 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002898
Ian Rogers19846512012-02-24 11:42:47 -08002899 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002900 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002901
Andreas Gampe7fc8f902014-08-25 15:05:04 -07002902 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002903
Ian Rogersdfb325e2013-10-30 01:00:44 -07002904 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002905 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002906 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2907 // Void return type.
Andreas Gampe35439ba2014-08-28 14:41:02 -07002908 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002909 klass->SetFinalizable();
2910 } else {
Ian Rogerscb6b0f32014-08-12 02:30:58 -07002911 std::string temp;
2912 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002913 // The Enum class declares a "final" finalize() method to prevent subclasses from
2914 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2915 // subclasses, so we exclude it here.
2916 // We also want to avoid setting the flag on Object, where we know that finalize() is
2917 // empty.
Ian Rogerscb6b0f32014-08-12 02:30:58 -07002918 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2919 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002920 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002921 }
2922 }
2923 }
2924 } else if (method_name[0] == '<') {
2925 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002926 bool is_init = (strcmp("<init>", method_name) == 0);
2927 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002928 if (UNLIKELY(!is_init && !is_clinit)) {
2929 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2930 } else {
2931 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2932 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002933 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002934 access_flags |= kAccConstructor;
2935 }
2936 }
2937 }
2938 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002939
Ian Rogers50b35e22012-10-04 10:09:15 -07002940 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002941 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002942}
2943
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002944void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002945 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002946 StackHandleScope<1> hs(self);
2947 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe35439ba2014-08-28 14:41:02 -07002948 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2949 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002950 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002951}
2952
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002953void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002954 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe35439ba2014-08-28 14:41:02 -07002955 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002956 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002957 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002958}
2959
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002960bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002961 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002962 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002963 mirror::DexCache* dex_cache = GetDexCache(i);
2964 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002965 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002966 }
2967 }
2968 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002969}
2970
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002971bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002972 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002973 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002974}
2975
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002976void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002977 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002978 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe35439ba2014-08-28 14:41:02 -07002979 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002980 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2981 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002982 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002983 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002984 if (log_new_dex_caches_roots_) {
2985 // TODO: This is not safe if we can remove dex caches.
2986 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2987 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002988}
2989
Brian Carlstromaded5f72011-10-07 17:15:04 -07002990void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002991 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002992 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002993 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002994 if (IsDexFileRegisteredLocked(dex_file)) {
2995 return;
2996 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002997 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002998 // Don't alloc while holding the lock, since allocation may need to
2999 // suspend all threads and another thread may need the dex_lock_ to
3000 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003001 StackHandleScope<1> hs(self);
3002 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe35439ba2014-08-28 14:41:02 -07003003 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3004 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003005 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003006 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003007 if (IsDexFileRegisteredLocked(dex_file)) {
3008 return;
3009 }
3010 RegisterDexFileLocked(dex_file, dex_cache);
3011 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003012}
3013
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003014void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003015 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003016 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003017 RegisterDexFileLocked(dex_file, dex_cache);
3018}
3019
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003020mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003021 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003022 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003023 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003024 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003025 if (dex_cache->GetDexFile() == &dex_file) {
3026 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003027 }
3028 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003029 // Search matching by location name.
3030 std::string location(dex_file.GetLocation());
3031 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003032 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003033 if (dex_cache->GetDexFile()->GetLocation() == location) {
3034 return dex_cache;
3035 }
3036 }
3037 // Failure, dump diagnostic and abort.
3038 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003039 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003040 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3041 }
3042 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Andreas Gampe35439ba2014-08-28 14:41:02 -07003043 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003044}
3045
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003046void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003047 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003048 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003049 mirror::DexCache* dex_cache = GetDexCache(i);
3050 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003051 }
3052}
3053
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003054mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003055 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe35439ba2014-08-28 14:41:02 -07003056 if (UNLIKELY(klass == nullptr)) {
3057 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003058 }
3059 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003060}
3061
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003062mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3063 Primitive::Type type) {
Andreas Gampe35439ba2014-08-28 14:41:02 -07003064 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003065 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003066 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003067 StackHandleScope<1> hs(self);
3068 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003069 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003070 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003071 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003072 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3073 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier564ff982014-11-06 16:35:45 -08003074 mirror::Class* existing = InsertClass(descriptor, primitive_class,
3075 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe35439ba2014-08-28 14:41:02 -07003076 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003077 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003078}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003079
Brian Carlstrombe977852011-07-19 14:54:54 -07003080// Create an array class (i.e. the class object for the array, not the
3081// array itself). "descriptor" looks like "[C" or "[[[[B" or
3082// "[Ljava/lang/String;".
3083//
3084// If "descriptor" refers to an array of primitives, look up the
3085// primitive type's internally-generated class object.
3086//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003087// "class_loader" is the class loader of the class that's referring to
3088// us. It's used to ensure that we're looking for the element type in
3089// the right context. It does NOT become the class loader for the
3090// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003091//
Andreas Gampe35439ba2014-08-28 14:41:02 -07003092// Returns nullptr with an exception raised on failure.
Mathieu Chartier564ff982014-11-06 16:35:45 -08003093mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003094 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003095 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003096 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003097 StackHandleScope<2> hs(self);
3098 Handle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1, class_loader)));
3099 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003100 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003101 // We need to accept erroneous classes as component types.
Mathieu Chartier564ff982014-11-06 16:35:45 -08003102 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3103 component_type.Assign(LookupClass(descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003104 if (component_type.Get() == nullptr) {
3105 DCHECK(self->IsExceptionPending());
3106 return nullptr;
3107 } else {
3108 self->ClearException();
3109 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003110 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003111 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3112 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3113 return nullptr;
3114 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003115 // See if the component type is already loaded. Array classes are
3116 // always associated with the class loader of their underlying
3117 // element type -- an array of Strings goes with the loader for
3118 // java/lang/String -- so we need to look for it there. (The
3119 // caller should have checked for the existence of the class
3120 // before calling here, but they did so with *their* class loader,
3121 // not the component type's loader.)
3122 //
3123 // If we find it, the caller adds "loader" to the class' initiating
3124 // loader list, which should prevent us from going through this again.
3125 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003126 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003127 // are the same, because our caller (FindClass) just did the
3128 // lookup. (Even if we get this wrong we still have correct behavior,
3129 // because we effectively do this lookup again when we add the new
3130 // class to the hash table --- necessary because of possible races with
3131 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003132 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartier564ff982014-11-06 16:35:45 -08003133 mirror::Class* new_class = LookupClass(descriptor, hash, component_type->GetClassLoader());
Andreas Gampe35439ba2014-08-28 14:41:02 -07003134 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003135 return new_class;
3136 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003137 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003138
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003139 // Fill out the fields in the Class.
3140 //
3141 // It is possible to execute some methods against arrays, because
3142 // all arrays are subclasses of java_lang_Object_, so we need to set
3143 // up a vtable. We can just point at the one in java_lang_Object_.
3144 //
3145 // Array classes are simple enough that we don't need to do a full
3146 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003147 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003148 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003149 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003150 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003151 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003152 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003153 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003154 } else if (strcmp(descriptor, class_roots_descriptors_[kJavaLangStringArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003155 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003156 } else if (strcmp(descriptor,
3157 class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003158 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003159 } else if (strcmp(descriptor,
3160 class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003161 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003162 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003163 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003164 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003165 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003166 }
3167 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003168 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003169 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003170 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003171 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003172 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003173 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003174 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003175 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe35439ba2014-08-28 14:41:02 -07003176 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003177 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003178 new_class->SetSuperClass(java_lang_Object);
3179 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003180 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003181 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003182 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07003183 {
3184 StackHandleScope<mirror::Class::kImtSize> hs(self,
3185 Runtime::Current()->GetImtUnimplementedMethod());
3186 new_class->PopulateEmbeddedImtAndVTable(&hs);
3187 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003188 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003189 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003190 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003191
3192
3193 // All arrays have java/lang/Cloneable and java/io/Serializable as
3194 // interfaces. We need to set that up here, so that stuff like
3195 // "instanceof" works right.
3196 //
3197 // Note: The GC could run during the call to FindSystemClass,
3198 // so we need to make sure the class object is GC-valid while we're in
3199 // there. Do this by clearing the interface list so the GC will just
3200 // think that the entries are null.
3201
3202
3203 // Use the single, global copies of "interfaces" and "iftable"
3204 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003205 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003206 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003207 CHECK(array_iftable != nullptr);
3208 new_class->SetIfTable(array_iftable);
3209 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003210
Elliott Hughes00626c22013-06-14 15:04:14 -07003211 // Inherit access flags from the component type.
3212 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3213 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3214 access_flags &= kAccJavaFlagsMask;
3215 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003216 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003217 access_flags |= kAccAbstract | kAccFinal;
3218 access_flags &= ~kAccInterface;
3219
3220 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003221
Mathieu Chartier564ff982014-11-06 16:35:45 -08003222 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003223 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003224 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003225 }
3226 // Another thread must have loaded the class after we
3227 // started but before we finished. Abandon what we've
3228 // done.
3229 //
3230 // (Yes, this happens.)
3231
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003232 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003233}
3234
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003235mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003236 switch (type) {
3237 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003238 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003239 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003240 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003241 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003242 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003243 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003244 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003245 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003246 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003247 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003248 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003249 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003250 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003251 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003252 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003253 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003254 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003255 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003256 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003257 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003258 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003259 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe35439ba2014-08-28 14:41:02 -07003260 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003261}
3262
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003263mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3264 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003265 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003266 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003267 std::string source;
Andreas Gampe35439ba2014-08-28 14:41:02 -07003268 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003269 source += " from ";
3270 source += dex_cache->GetLocation()->ToModifiedUtf8();
3271 }
3272 LOG(INFO) << "Loaded class " << descriptor << source;
3273 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003274 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08003275 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe35439ba2014-08-28 14:41:02 -07003276 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003277 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003278 }
Andreas Gampe35439ba2014-08-28 14:41:02 -07003279 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003280 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003281 // Check a class loaded with the system class loader matches one in the image if the class
3282 // is in the image.
3283 existing = LookupClassFromImage(descriptor);
Andreas Gampe35439ba2014-08-28 14:41:02 -07003284 if (existing != nullptr) {
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08003285 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003286 }
3287 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003288 VerifyObject(klass);
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08003289 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003290 if (log_new_class_table_roots_) {
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08003291 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003292 }
Andreas Gampe35439ba2014-08-28 14:41:02 -07003293 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003294}
3295
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003296mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3297 size_t hash) {
3298 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier564ff982014-11-06 16:35:45 -08003299 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
3300 hash);
3301 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003302 CHECK(klass->IsProxyClass());
3303 return nullptr;
3304 }
3305
Mathieu Chartier564ff982014-11-06 16:35:45 -08003306 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003307 CHECK_NE(existing, klass) << descriptor;
3308 CHECK(!existing->IsResolved()) << descriptor;
3309 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3310
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003311 CHECK(!klass->IsTemp()) << descriptor;
3312 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3313 dex_cache_image_class_lookup_required_) {
3314 // Check a class loaded with the system class loader matches one in the image if the class
3315 // is in the image.
3316 existing = LookupClassFromImage(descriptor);
3317 if (existing != nullptr) {
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08003318 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003319 }
3320 }
3321 VerifyObject(klass);
3322
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08003323 // Update the element in the hash set.
Mathieu Chartier564ff982014-11-06 16:35:45 -08003324 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003325 if (log_new_class_table_roots_) {
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08003326 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003327 }
3328
3329 return existing;
3330}
3331
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08003332bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003333 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08003334 auto pair = std::make_pair(descriptor, class_loader);
3335 auto it = class_table_.Find(pair);
3336 if (it != class_table_.end()) {
3337 class_table_.Erase(it);
3338 return true;
3339 }
3340 it = pre_zygote_class_table_.Find(pair);
3341 if (it != pre_zygote_class_table_.end()) {
3342 pre_zygote_class_table_.Erase(it);
3343 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08003344 }
3345 return false;
3346}
3347
Mathieu Chartier564ff982014-11-06 16:35:45 -08003348mirror::Class* ClassLinker::LookupClass(const char* descriptor, size_t hash,
3349 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003350 {
3351 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3352 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe35439ba2014-08-28 14:41:02 -07003353 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003354 return result;
3355 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003356 }
Andreas Gampe35439ba2014-08-28 14:41:02 -07003357 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3358 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003359 } else {
3360 // Lookup failed but need to search dex_caches_.
3361 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe35439ba2014-08-28 14:41:02 -07003362 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003363 InsertClass(descriptor, result, hash);
3364 } else {
3365 // Searching the image dex files/caches failed, we don't want to get into this situation
3366 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3367 // classes into the class table.
Ian Rogerscc2f2392014-08-29 20:19:11 -07003368 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003369 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3370 MoveImageClassesToClassTable();
3371 }
3372 }
3373 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003374 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003375}
3376
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003377mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08003378 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003379 size_t hash) {
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08003380 auto descriptor_pair = std::make_pair(descriptor, class_loader);
3381 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
3382 if (it == pre_zygote_class_table_.end()) {
3383 it = class_table_.FindWithHash(descriptor_pair, hash);
3384 if (it == class_table_.end()) {
3385 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07003386 }
3387 }
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08003388 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003389}
3390
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003391static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3392 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3393 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe35439ba2014-08-28 14:41:02 -07003394 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003395 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3396 return root->AsObjectArray<mirror::DexCache>();
3397}
3398
3399void ClassLinker::MoveImageClassesToClassTable() {
3400 Thread* self = Thread::Current();
3401 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3402 if (!dex_cache_image_class_lookup_required_) {
3403 return; // All dex cache classes are already in the class table.
3404 }
3405 const char* old_no_suspend_cause =
3406 self->StartAssertNoThreadSuspension("Moving image classes to class table");
3407 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogerscb6b0f32014-08-12 02:30:58 -07003408 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003409 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3410 mirror::DexCache* dex_cache = dex_caches->Get(i);
3411 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3412 for (int32_t j = 0; j < types->GetLength(); j++) {
3413 mirror::Class* klass = types->Get(j);
Andreas Gampe35439ba2014-08-28 14:41:02 -07003414 if (klass != nullptr) {
3415 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogerscb6b0f32014-08-12 02:30:58 -07003416 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartier564ff982014-11-06 16:35:45 -08003417 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe35439ba2014-08-28 14:41:02 -07003418 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3419 if (existing != nullptr) {
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08003420 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003421 << PrettyClassAndClassLoader(klass);
3422 } else {
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08003423 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003424 if (log_new_class_table_roots_) {
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08003425 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003426 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003427 }
3428 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003429 }
3430 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003431 dex_cache_image_class_lookup_required_ = false;
3432 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3433}
3434
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08003435void ClassLinker::MoveClassTableToPreZygote() {
3436 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3437 DCHECK(pre_zygote_class_table_.Empty());
3438 pre_zygote_class_table_ = std::move(class_table_);
3439 class_table_.Clear();
3440}
3441
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003442mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
3443 Thread* self = Thread::Current();
3444 const char* old_no_suspend_cause =
3445 self->StartAssertNoThreadSuspension("Image class lookup");
3446 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3447 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3448 mirror::DexCache* dex_cache = dex_caches->Get(i);
3449 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003450 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003451 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe35439ba2014-08-28 14:41:02 -07003452 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003453 const DexFile::TypeId* type_id =
3454 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe35439ba2014-08-28 14:41:02 -07003455 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003456 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3457 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe35439ba2014-08-28 14:41:02 -07003458 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003459 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3460 return klass;
3461 }
3462 }
3463 }
3464 }
3465 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Andreas Gampe35439ba2014-08-28 14:41:02 -07003466 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003467}
3468
3469void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3470 result.clear();
3471 if (dex_cache_image_class_lookup_required_) {
3472 MoveImageClassesToClassTable();
3473 }
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08003474 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3475 while (true) {
3476 auto it = class_table_.Find(descriptor);
3477 if (it == class_table_.end()) {
3478 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003479 }
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08003480 result.push_back(it->Read());
3481 class_table_.Erase(it);
3482 }
3483 for (mirror::Class* k : result) {
3484 class_table_.Insert(GcRoot<mirror::Class>(k));
3485 }
3486 size_t pre_zygote_start = result.size();
3487 // Now handle the pre zygote table.
3488 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
3489 // called from the debugger.
3490 while (true) {
3491 auto it = pre_zygote_class_table_.Find(descriptor);
3492 if (it == pre_zygote_class_table_.end()) {
3493 break;
3494 }
3495 result.push_back(it->Read());
3496 pre_zygote_class_table_.Erase(it);
3497 }
3498 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
3499 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003500 }
3501}
3502
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003503void ClassLinker::VerifyClass(Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003504 // TODO: assert that the monitor on the Class is held
Ian Rogers1f539342012-10-03 21:09:42 -07003505 Thread* self = Thread::Current();
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003506 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003507
Ian Rogers9ffb0392012-09-10 11:56:50 -07003508 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampe3892cf82014-09-11 10:59:33 -07003509 if (klass->IsVerified()) {
Andreas Gampedf1532b2014-09-10 19:48:05 -07003510 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003511 return;
3512 }
Andreas Gampe3892cf82014-09-11 10:59:33 -07003513 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3514 return;
3515 }
jeffhao98eacac2011-09-14 16:11:53 -07003516
Ian Rogers9ffb0392012-09-10 11:56:50 -07003517 // The class might already be erroneous, for example at compile time if we attempted to verify
3518 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003519 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003520 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003521 return;
3522 }
3523
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003524 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003525 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003526 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003527 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003528 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003529 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003530 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003531 }
jeffhao98eacac2011-09-14 16:11:53 -07003532
Jeff Hao4a200f52014-04-01 14:58:49 -07003533 // Skip verification if disabled.
3534 if (!Runtime::Current()->IsVerificationEnabled()) {
3535 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampedf1532b2014-09-10 19:48:05 -07003536 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003537 return;
3538 }
3539
Ian Rogers9ffb0392012-09-10 11:56:50 -07003540 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003541 StackHandleScope<2> hs(self);
3542 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe35439ba2014-08-28 14:41:02 -07003543 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003544 // Acquire lock to prevent races on verifying the super class.
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003545 ObjectLock<mirror::Class> lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003546
3547 if (!super->IsVerified() && !super->IsErroneous()) {
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003548 VerifyClass(super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003549 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003550 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003551 std::string error_msg(
3552 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3553 PrettyDescriptor(klass.Get()).c_str(),
3554 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003555 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003556 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3557 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003558 self->ClearException();
3559 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003560 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3561 if (cause.Get() != nullptr) {
3562 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003563 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003564 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003565 if (Runtime::Current()->IsCompiler()) {
3566 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3567 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003568 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003569 return;
3570 }
3571 }
3572
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003573 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003574 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003575 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003576 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003577 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003578 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003579 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003580 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003581 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3582 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003583 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003584 return;
3585 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003586 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003587 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003588 if (!preverified) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003589 verifier_failure = verifier::MethodVerifier::VerifyClass(klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003590 Runtime::Current()->IsCompiler(),
3591 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003592 }
3593 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003594 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003595 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003596 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3597 << " because: " << error_msg;
3598 }
Ian Rogers1f539342012-10-03 21:09:42 -07003599 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003600 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003601 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003602 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003603 // Even though there were no verifier failures we need to respect whether the super-class
3604 // was verified or requiring runtime reverification.
Andreas Gampe35439ba2014-08-28 14:41:02 -07003605 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003606 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003607 } else {
3608 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003609 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003610 // Pretend a soft failure occured so that we don't consider the class verified below.
3611 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003612 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003613 } else {
3614 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3615 // Soft failures at compile time should be retried at runtime. Soft
3616 // failures at runtime will be handled by slow paths in the generated
3617 // code. Set status accordingly.
3618 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003619 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003620 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003621 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe3892cf82014-09-11 10:59:33 -07003622 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3623 // later.
3624 klass->SetAccessFlags(klass->GetAccessFlags() | kAccPreverified);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003625 }
3626 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003627 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003628 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003629 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3630 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003631 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003632 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003633 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003634 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003635 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003636 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003637 // Let the interpreter know it by setting the kAccPreverified flag onto each
3638 // method.
3639 // Note: we're going here during compilation and at runtime. When we set the
3640 // kAccPreverified flag when compiling image classes, the flag is recorded
3641 // in the image and is set when loading the image.
Andreas Gampedf1532b2014-09-10 19:48:05 -07003642 EnsurePreverifiedMethods(klass);
3643 }
3644}
3645
3646void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
3647 if ((klass->GetAccessFlags() & kAccPreverified) == 0) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003648 klass->SetPreverifiedFlagOnAllMethods();
Andreas Gampedf1532b2014-09-10 19:48:05 -07003649 klass->SetAccessFlags(klass->GetAccessFlags() | kAccPreverified);
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003650 }
jeffhao98eacac2011-09-14 16:11:53 -07003651}
3652
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003653bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3654 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003655 // If we're compiling, we can only verify the class using the oat file if
3656 // we are not compiling the image or if the class we're verifying is not part of
3657 // the app. In other words, we will only check for preverification of bootclasspath
3658 // classes.
3659 if (Runtime::Current()->IsCompiler()) {
3660 // Are we compiling the bootclasspath?
3661 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3662 return false;
3663 }
3664 // We are compiling an app (not the image).
3665
3666 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe35439ba2014-08-28 14:41:02 -07003667 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003668 return false;
3669 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003670 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003671
Vladimir Markobe4e6432014-09-05 14:01:17 +01003672 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe35439ba2014-08-28 14:41:02 -07003673 // In case we run without an image there won't be a backing oat file.
3674 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003675 return false;
3676 }
3677
Sebastien Hertzcad417c2014-12-09 19:08:15 +01003678 // We may be running with a preopted oat file but without image. In this case,
3679 // we don't skip verification of preverified classes to ensure we initialize
3680 // dex caches with all types resolved during verification.
3681 if (!Runtime::Current()->IsCompiler() &&
3682 !Runtime::Current()->GetHeap()->HasImageSpace()) {
3683 return false;
3684 }
3685
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003686 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003687 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003688 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3689 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003690 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003691 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003692 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003693 // Compile time verification failed with a soft error. Compile time verification can fail
3694 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003695 // class ... {
3696 // Foo x;
3697 // .... () {
3698 // if (...) {
3699 // v1 gets assigned a type of resolved class Foo
3700 // } else {
3701 // v1 gets assigned a type of unresolved class Bar
3702 // }
3703 // iput x = v1
3704 // } }
3705 // when we merge v1 following the if-the-else it results in Conflict
3706 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3707 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3708 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3709 // at compile time).
3710 return false;
3711 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003712 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003713 // Compile time verification failed with a hard error. This is caused by invalid instructions
3714 // in the class. These errors are unrecoverable.
3715 return false;
3716 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003717 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003718 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3719 // not loading the class.
3720 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3721 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003722 return false;
3723 }
Ian Rogerscb6b0f32014-08-12 02:30:58 -07003724 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003725 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003726 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogerscb6b0f32014-08-12 02:30:58 -07003727 << klass->GetDescriptor(&temp);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003728
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003729 return false;
3730}
3731
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003732void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003733 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003734 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3735 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3736 }
3737 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3738 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3739 }
3740}
3741
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003742void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003743 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003744 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3745 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe35439ba2014-08-28 14:41:02 -07003746 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003747 return; // native or abstract method
3748 }
3749 if (code_item->tries_size_ == 0) {
3750 return; // nothing to process
3751 }
3752 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
3753 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3754 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3755 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3756 CatchHandlerIterator iterator(handlers_ptr);
3757 for (; iterator.HasNext(); iterator.Next()) {
3758 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3759 // unresolved exception types will be ignored by exception delivery
3760 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003761 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe35439ba2014-08-28 14:41:02 -07003762 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003763 DCHECK(Thread::Current()->IsExceptionPending());
3764 Thread::Current()->ClearException();
3765 }
3766 }
3767 }
3768 handlers_ptr = iterator.EndDataPointer();
3769 }
3770}
3771
Brian Carlstromea46f952013-07-30 01:26:50 -07003772static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003773static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003774 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003775
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003776mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003777 jobjectArray interfaces, jobject loader,
3778 jobjectArray methods, jobjectArray throws) {
3779 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003780 StackHandleScope<8> hs(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003781 Handle<mirror::Class> klass(hs.NewHandle(
3782 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe35439ba2014-08-28 14:41:02 -07003783 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003784 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe35439ba2014-08-28 14:41:02 -07003785 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003786 }
Andreas Gampe35439ba2014-08-28 14:41:02 -07003787 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003788 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampedf1532b2014-09-10 19:48:05 -07003789 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3790 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003791 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003792 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003793 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003794 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003795 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003796 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003797
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003798 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003799 {
3800 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe35439ba2014-08-28 14:41:02 -07003801 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003802 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe35439ba2014-08-28 14:41:02 -07003803 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003804 }
3805 klass->SetSFields(sfields);
3806 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003807 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3808 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003809 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3810 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003811 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003812 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003813 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003814 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003815 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003816 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003817 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3818 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003819 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3820 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003821 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003822 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003823 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003824 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003825 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003826 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003827 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003828
Ian Rogers466bb252011-10-14 03:29:56 -07003829 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003830 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003831 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003832 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003833 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003834 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003835 }
3836 klass->SetDirectMethods(directs);
3837 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003838 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003839 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003840 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003841 }
3842 klass->SetDirectMethod(0, constructor);
3843 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003844
Mathieu Chartier590fee92013-09-13 13:46:47 -07003845 // Create virtual method using specified prototypes.
3846 size_t num_virtual_methods =
3847 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003848 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003849 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3850 num_virtual_methods);
Andreas Gampe35439ba2014-08-28 14:41:02 -07003851 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003852 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe35439ba2014-08-28 14:41:02 -07003853 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003854 }
3855 klass->SetVirtualMethods(virtuals);
3856 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003857 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003858 StackHandleScope<1> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003859 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3860 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003861 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003862 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003863 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003864 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003865 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003866 }
3867 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003868 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003869
3870 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003871 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003872 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003873
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003874 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3875 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003876 {
Andreas Gampe35439ba2014-08-28 14:41:02 -07003877 // Must hold lock on object when resolved.
3878 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003879 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003880 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003881 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003882 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003883 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003884 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003885 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003886 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003887
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003888 CHECK(klass->IsRetired());
3889 CHECK_NE(klass.Get(), new_class);
3890 klass.Assign(new_class);
3891
3892 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe35439ba2014-08-28 14:41:02 -07003893 interfaces_sfield->SetObject<false>(klass.Get(),
3894 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003895 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe35439ba2014-08-28 14:41:02 -07003896 throws_sfield->SetObject<false>(klass.Get(),
3897 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003898
3899 {
3900 // Lock on klass is released. Lock new class object.
3901 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003902 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003903 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003904
3905 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003906 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003907 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003908 CheckProxyConstructor(klass->GetDirectMethod(0));
3909 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003910 StackHandleScope<2> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003911 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3912 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003913 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003914 Handle<mirror::ArtMethod> virtual_method(hs.NewHandle(klass->GetVirtualMethod(i)));
3915 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003916 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003917
Mathieu Chartier590fee92013-09-13 13:46:47 -07003918 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003919 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003920 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003921 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3922
3923 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003924 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003925 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003926
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003927 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003928 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003929 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003930 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003931 }
Mathieu Chartier564ff982014-11-06 16:35:45 -08003932 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3933 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003934 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003935 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003936}
3937
Ian Rogersef7d42f2014-01-06 12:55:46 -08003938std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003939 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003940 mirror::String* name = proxy_class->GetName();
Andreas Gampe35439ba2014-08-28 14:41:02 -07003941 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003942 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3943}
3944
Ian Rogersef7d42f2014-01-06 12:55:46 -08003945mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3946 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003947 DCHECK(proxy_class->IsProxyClass());
3948 DCHECK(proxy_method->IsProxyMethod());
3949 // Locate the dex cache of the original interface/Object
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003950 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003951 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003952 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003953 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003954 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003955 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003956 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003957 break;
3958 }
3959 }
3960 }
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003961 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003962 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003963 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe4ef12f52014-07-31 16:23:49 -07003964 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003965 return resolved_method;
3966}
3967
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003968
Brian Carlstromea46f952013-07-30 01:26:50 -07003969mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003970 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003971 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003972 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003973 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003974 proxy_class->GetDirectMethods();
Piotr Jastrzebski3b021bf2015-05-05 16:19:00 +01003975 CHECK_EQ(proxy_direct_methods->GetLength(), 19);
Brian Carlstromea46f952013-07-30 01:26:50 -07003976 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertz440d3da2014-08-27 15:32:56 +02003977 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3978 // constructor method.
3979 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3980 proxy_constructor);
Jeff Hao95b4c652014-08-14 17:18:52 -07003981 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3982 // code_ too)
Jeff Hao4bf8d112014-07-24 16:26:09 -07003983 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3984 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003985 CHECK(self->IsExceptionPending()); // OOME.
Jeff Hao4bf8d112014-07-24 16:26:09 -07003986 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003987 }
Ian Rogers466bb252011-10-14 03:29:56 -07003988 // Make this constructor public and fix the class to be our Proxy version
3989 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003990 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003991 return constructor;
3992}
3993
Brian Carlstromea46f952013-07-30 01:26:50 -07003994static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003995 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003996 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003997 CHECK_STREQ(constructor->GetName(), "<init>");
3998 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3999 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004000 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004001}
4002
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004003mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004004 Handle<mirror::Class> klass,
4005 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004006 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4007 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08004008 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004009 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004010 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004011 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07004012 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe35439ba2014-08-28 14:41:02 -07004013 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004014 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe35439ba2014-08-28 14:41:02 -07004015 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004016 }
Ian Rogers466bb252011-10-14 03:29:56 -07004017
4018 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
4019 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004020 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07004021 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004022
Ian Rogers466bb252011-10-14 03:29:56 -07004023 // At runtime the method looks like a reference and argument saving method, clone the code
4024 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004025 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogers63bc11e2014-09-18 08:56:45 -07004026#if defined(ART_USE_PORTABLE_COMPILER)
Ian Rogersef7d42f2014-01-06 12:55:46 -08004027 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Ian Rogers63bc11e2014-09-18 08:56:45 -07004028#endif
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07004029 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08004030
Ian Rogersc2b44472011-12-14 21:17:17 -08004031 return method;
4032}
Jesse Wilson95caa792011-10-12 18:14:17 -04004033
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004034static void CheckProxyMethod(Handle<mirror::ArtMethod> method, Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004035 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004036 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004037 CHECK(!prototype->IsFinal());
4038 CHECK(method->IsFinal());
4039 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004040
4041 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4042 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe4ef12f52014-07-31 16:23:49 -07004043 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4044 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004045 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4046
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004047 MethodHelper mh(method);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004048 MethodHelper mh2(prototype);
4049 CHECK_STREQ(method->GetName(), prototype->GetName());
4050 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004051 // More complex sanity - via dex cache
Ian Rogers19846512012-02-24 11:42:47 -08004052 CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004053}
4054
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004055static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4056 bool can_init_parents)
4057 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004058 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004059 return true;
4060 }
4061 if (!can_init_statics) {
4062 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004063 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe35439ba2014-08-28 14:41:02 -07004064 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004065 return false;
4066 }
4067 // Check if there are encoded static values needing initialization.
4068 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004069 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe35439ba2014-08-28 14:41:02 -07004070 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004071 if (dex_class_def->static_values_off_ != 0) {
4072 return false;
4073 }
4074 }
4075 }
4076 if (!klass->IsInterface() && klass->HasSuperClass()) {
4077 mirror::Class* super_class = klass->GetSuperClass();
4078 if (!can_init_parents && !super_class->IsInitialized()) {
4079 return false;
4080 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004081 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004082 return false;
4083 }
4084 }
4085 }
4086 return true;
4087}
4088
Mathieu Chartier590fee92013-09-13 13:46:47 -07004089bool ClassLinker::IsInitialized() const {
4090 return init_done_;
4091}
4092
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004093bool ClassLinker::InitializeClass(Handle<mirror::Class> klass, bool can_init_statics,
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004094 bool can_init_parents) {
4095 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4096
4097 // Are we already initialized and therefore done?
4098 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4099 // an initialized class will never change its state.
4100 if (klass->IsInitialized()) {
4101 return true;
4102 }
4103
4104 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004105 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004106 return false;
4107 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004108
Carl Shapirob5573532011-07-12 18:22:59 -07004109 Thread* self = Thread::Current();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004110 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004111 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004112 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004113
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004114 // Re-check under the lock in case another thread initialized ahead of us.
4115 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004116 return true;
4117 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004118
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004119 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004120 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004121 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromd1422f82011-09-28 11:37:09 -07004122 return false;
4123 }
4124
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004125 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004126
4127 if (!klass->IsVerified()) {
jeffhao98eacac2011-09-14 16:11:53 -07004128 VerifyClass(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004129 if (!klass->IsVerified()) {
4130 // We failed to verify, expect either the klass to be erroneous or verification failed at
4131 // compile time.
4132 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004133 CHECK(self->IsExceptionPending());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004134 } else {
4135 CHECK(Runtime::Current()->IsCompiler());
4136 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004137 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004138 return false;
Mathieu Chartier58c016c2014-08-27 15:28:28 -07004139 } else {
4140 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004141 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004142 }
4143
Brian Carlstromd1422f82011-09-28 11:37:09 -07004144 // If the class is kStatusInitializing, either this thread is
4145 // initializing higher up the stack or another thread has beat us
4146 // to initializing and we need to wait. Either way, this
4147 // invocation of InitializeClass will not be responsible for
4148 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004149 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier58c016c2014-08-27 15:28:28 -07004150 // Could have got an exception during verification.
4151 if (self->IsExceptionPending()) {
4152 return false;
4153 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004154 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004155 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004156 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004157 return true;
4158 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004159 // No. That's fine. Wait for another thread to finish initializing.
4160 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004161 }
4162
4163 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004164 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004165 return false;
4166 }
4167
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004168 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004169
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004170 // From here out other threads may observe that we're initializing and so changes of state
4171 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004172 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004173 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004174
4175 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004176 }
4177
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004178 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004179 if (!klass->IsInterface() && klass->HasSuperClass()) {
4180 mirror::Class* super_class = klass->GetSuperClass();
4181 if (!super_class->IsInitialized()) {
4182 CHECK(!super_class->IsInterface());
4183 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004184 StackHandleScope<1> hs(self);
4185 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
4186 bool super_initialized = InitializeClass(handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004187 if (!super_initialized) {
4188 // The super class was verified ahead of entering initializing, we should only be here if
4189 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004190 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004191 << "Super class initialization failed for "
4192 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004193 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004194 << "\nPending exception:\n"
Andreas Gampe35439ba2014-08-28 14:41:02 -07004195 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004196 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004197 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004198 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004199 return false;
4200 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004201 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004202 }
4203
Mathieu Chartierbfb21582014-10-28 13:57:04 -07004204 const size_t num_static_fields = klass->NumStaticFields();
4205 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004206 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe35439ba2014-08-28 14:41:02 -07004207 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004208 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004209 StackHandleScope<2> hs(self);
4210 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004211 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartierbfb21582014-10-28 13:57:04 -07004212
4213 // Eagerly fill in static fields so that the we don't have to do as many expensive
4214 // Class::FindStaticField in ResolveField.
4215 for (size_t i = 0; i < num_static_fields; ++i) {
4216 mirror::ArtField* field = klass->GetStaticField(i);
4217 const uint32_t field_idx = field->GetDexFieldIndex();
4218 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
4219 if (resolved_field == nullptr) {
4220 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartiera9ca9ac2014-10-28 18:23:02 -07004221 } else {
4222 DCHECK_EQ(field, resolved_field);
Mathieu Chartierbfb21582014-10-28 13:57:04 -07004223 }
4224 }
4225
Mathieu Chartier590fee92013-09-13 13:46:47 -07004226 EncodedStaticFieldValueIterator it(dex_file, &dex_cache, &class_loader,
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004227 this, *dex_class_def);
4228 if (it.HasNext()) {
4229 CHECK(can_init_statics);
Brian Carlstromf3632832014-05-20 15:36:53 -07004230 // We reordered the fields, so we need to be able to map the
4231 // field indexes to the right fields.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004232 SafeMap<uint32_t, mirror::ArtField*> field_map;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004233 ConstructFieldMap(dex_file, *dex_class_def, klass.Get(), field_map);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004234 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004235 if (Runtime::Current()->IsActiveTransaction()) {
4236 it.ReadValueToField<true>(field_map.Get(i));
4237 } else {
4238 it.ReadValueToField<false>(field_map.Get(i));
4239 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004240 }
4241 }
4242 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004243
Ian Rogersd91d6d62013-09-25 20:26:14 -07004244 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe35439ba2014-08-28 14:41:02 -07004245 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004246 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004247 JValue result;
Andreas Gampe35439ba2014-08-28 14:41:02 -07004248 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004249 }
4250
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004251 uint64_t t1 = NanoTime();
4252
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004253 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004254 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004255 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004256
4257 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07004258 WrapExceptionInInitializer();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004259 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004260 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004261 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004262 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4263 RuntimeStats* thread_stats = self->GetStats();
4264 ++global_stats->class_init_count;
4265 ++thread_stats->class_init_count;
4266 global_stats->class_init_time_ns += (t1 - t0);
4267 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004268 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004269 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004270 if (VLOG_IS_ON(class_linker)) {
Ian Rogerscb6b0f32014-08-12 02:30:58 -07004271 std::string temp;
4272 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004273 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004274 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004275 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004276 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004277 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004278 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004279 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004280}
4281
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004282bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004283 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004284 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004285 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004286 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004287 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004288 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004289
4290 // When we wake up, repeat the test for init-in-progress. If
4291 // there's an exception pending (only possible if
4292 // "interruptShouldThrow" was set), bail out.
4293 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07004294 WrapExceptionInInitializer();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004295 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004296 return false;
4297 }
4298 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004299 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004300 continue;
4301 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004302 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004303 // Compile time initialization failed.
4304 return false;
4305 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004306 if (klass->IsErroneous()) {
4307 // The caller wants an exception, but it was thrown in a
4308 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004309 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004310 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07004311 return false;
4312 }
4313 if (klass->IsInitialized()) {
4314 return true;
4315 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004316 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004317 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004318 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004319 LOG(FATAL) << "Not Reached" << PrettyClass(klass.Get());
Brian Carlstromd1422f82011-09-28 11:37:09 -07004320}
4321
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004322bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004323 if (klass->IsInterface()) {
4324 return true;
4325 }
Ian Rogers151f2212014-05-06 11:27:27 -07004326 // Begin with the methods local to the superclass.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004327 StackHandleScope<2> hs(Thread::Current());
4328 MethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4329 MethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004330 if (klass->HasSuperClass() &&
4331 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004332 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
4333 mh.ChangeMethod(klass->GetVTableEntry(i));
4334 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004335 if (mh.GetMethod() != super_mh.GetMethod() &&
4336 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
4337 ThrowLinkageError(klass.Get(),
4338 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004339 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004340 PrettyMethod(mh.GetMethod()).c_str(),
4341 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004342 return false;
4343 }
4344 }
4345 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004346 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004347 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4348 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4349 for (uint32_t j = 0; j < num_methods; ++j) {
4350 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4351 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004352 if (mh.GetMethod() != super_mh.GetMethod() &&
4353 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
4354 ThrowLinkageError(klass.Get(),
4355 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004356 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004357 PrettyMethod(mh.GetMethod()).c_str(),
4358 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004359 return false;
4360 }
4361 }
4362 }
4363 }
4364 return true;
4365}
4366
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004367bool ClassLinker::EnsureInitialized(Handle<mirror::Class> c, bool can_init_fields,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004368 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004369 DCHECK(c.Get() != nullptr);
Mathieu Chartier58c016c2014-08-27 15:28:28 -07004370 if (c->IsInitialized()) {
Andreas Gampedf1532b2014-09-10 19:48:05 -07004371 EnsurePreverifiedMethods(c);
Mathieu Chartier58c016c2014-08-27 15:28:28 -07004372 return true;
4373 }
4374 const bool success = InitializeClass(c, can_init_fields, can_init_parents);
4375 Thread* self = Thread::Current();
4376 if (!success) {
4377 if (can_init_fields && can_init_parents) {
4378 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4379 }
4380 } else {
4381 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004382 }
4383 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004384}
4385
Elliott Hughes5fe594f2011-09-08 12:33:17 -07004386void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Mathieu Chartier590fee92013-09-13 13:46:47 -07004387 mirror::Class* c,
4388 SafeMap<uint32_t, mirror::ArtField*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07004389 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07004390 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004391 StackHandleScope<2> hs(Thread::Current());
4392 Handle<mirror::DexCache> dex_cache(hs.NewHandle(c->GetDexCache()));
4393 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(c->GetClassLoader()));
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004394 CHECK(!kMovingFields);
Ian Rogers0571d352011-11-03 19:51:38 -07004395 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004396 field_map.Put(i, ResolveField(dex_file, it.GetMemberIndex(), dex_cache, class_loader, true));
Elliott Hughes5fe594f2011-09-08 12:33:17 -07004397 }
4398}
4399
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004400void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4401 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4402 if (fields != nullptr) {
4403 for (int index = 0; index < fields->GetLength(); index ++) {
4404 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4405 fields->Get(index)->SetDeclaringClass(new_class);
4406 }
4407 }
4408 }
4409
4410 fields = new_class->GetSFields();
4411 if (fields != nullptr) {
4412 for (int index = 0; index < fields->GetLength(); index ++) {
4413 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4414 fields->Get(index)->SetDeclaringClass(new_class);
4415 }
4416 }
4417 }
4418
4419 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4420 if (methods != nullptr) {
4421 for (int index = 0; index < methods->GetLength(); index ++) {
4422 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4423 methods->Get(index)->SetDeclaringClass(new_class);
4424 }
4425 }
4426 }
4427
4428 methods = new_class->GetVirtualMethods();
4429 if (methods != nullptr) {
4430 for (int index = 0; index < methods->GetLength(); index ++) {
4431 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4432 methods->Get(index)->SetDeclaringClass(new_class);
4433 }
4434 }
4435 }
4436}
4437
4438bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4439 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4440 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004441 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004442
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004443 if (!LinkSuperClass(klass)) {
4444 return false;
4445 }
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07004446 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
4447 self, Runtime::Current()->GetImtUnimplementedMethod());
4448 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004449 return false;
4450 }
4451 if (!LinkInstanceFields(klass)) {
4452 return false;
4453 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004454 size_t class_size;
4455 if (!LinkStaticFields(klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004456 return false;
4457 }
4458 CreateReferenceInstanceOffsets(klass);
4459 CreateReferenceStaticOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004460 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004461
4462 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4463 // We don't need to retire this class as it has no embedded tables or it was created the
4464 // correct size during class linker initialization.
4465 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4466
4467 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07004468 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004469 }
4470
4471 // This will notify waiters on klass that saw the not yet resolved
4472 // class in the class_table_ during EnsureResolved.
4473 klass->SetStatus(mirror::Class::kStatusResolved, self);
4474 *new_class = klass.Get();
4475 } else {
4476 CHECK(!klass->IsResolved());
4477 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07004478 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe35439ba2014-08-28 14:41:02 -07004479 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004480 CHECK(self->IsExceptionPending()); // Expect an OOME.
4481 klass->SetStatus(mirror::Class::kStatusError, self);
4482 return false;
4483 }
4484
4485 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4486 StackHandleScope<1> hs(self);
4487 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4488 ObjectLock<mirror::Class> lock(self, new_class_h);
4489
4490 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4491
Mathieu Chartier564ff982014-11-06 16:35:45 -08004492 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
4493 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe35439ba2014-08-28 14:41:02 -07004494 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004495
4496 // This will notify waiters on temp class that saw the not yet resolved class in the
4497 // class_table_ during EnsureResolved.
4498 klass->SetStatus(mirror::Class::kStatusRetired, self);
4499
4500 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4501 // This will notify waiters on new_class that saw the not yet resolved
4502 // class in the class_table_ during EnsureResolved.
4503 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004504 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004505 return true;
4506}
4507
Andreas Gampe15a33b32014-11-06 16:52:58 -08004508static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
4509 size_t* virtual_methods,
4510 size_t* direct_methods,
4511 size_t* static_fields,
4512 size_t* instance_fields) {
4513 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
4514
4515 while (dex_data.HasNextStaticField()) {
4516 dex_data.Next();
4517 (*static_fields)++;
4518 }
4519 while (dex_data.HasNextInstanceField()) {
4520 dex_data.Next();
4521 (*instance_fields)++;
4522 }
4523 while (dex_data.HasNextDirectMethod()) {
4524 (*direct_methods)++;
4525 dex_data.Next();
4526 }
4527 while (dex_data.HasNextVirtualMethod()) {
4528 (*virtual_methods)++;
4529 dex_data.Next();
4530 }
4531 DCHECK(!dex_data.HasNext());
4532}
4533
4534static void DumpClass(std::ostream& os,
4535 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
4536 const char* suffix) {
4537 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
4538 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
4539 os << " Static fields:\n";
4540 while (dex_data.HasNextStaticField()) {
4541 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
4542 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
4543 dex_data.Next();
4544 }
4545 os << " Instance fields:\n";
4546 while (dex_data.HasNextInstanceField()) {
4547 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
4548 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
4549 dex_data.Next();
4550 }
4551 os << " Direct methods:\n";
4552 while (dex_data.HasNextDirectMethod()) {
4553 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
4554 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
4555 dex_data.Next();
4556 }
4557 os << " Virtual methods:\n";
4558 while (dex_data.HasNextVirtualMethod()) {
4559 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
4560 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
4561 dex_data.Next();
4562 }
4563}
4564
4565static std::string DumpClasses(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
4566 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2) {
4567 std::ostringstream os;
4568 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
4569 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
4570 return os.str();
4571}
4572
4573
4574// Very simple structural check on whether the classes match. Only compares the number of
4575// methods and fields.
4576static bool SimpleStructuralCheck(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
4577 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2,
4578 std::string* error_msg) {
4579 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
4580 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
4581
4582 // Counters for current dex file.
4583 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
4584 CountMethodsAndFields(dex_data1, &dex_virtual_methods1, &dex_direct_methods1, &dex_static_fields1,
4585 &dex_instance_fields1);
4586 // Counters for compile-time dex file.
4587 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
4588 CountMethodsAndFields(dex_data2, &dex_virtual_methods2, &dex_direct_methods2, &dex_static_fields2,
4589 &dex_instance_fields2);
4590
4591 if (dex_virtual_methods1 != dex_virtual_methods2) {
4592 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4593 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s", dex_virtual_methods1,
4594 dex_virtual_methods2, class_dump.c_str());
4595 return false;
4596 }
4597 if (dex_direct_methods1 != dex_direct_methods2) {
4598 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4599 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s", dex_direct_methods1,
4600 dex_direct_methods2, class_dump.c_str());
4601 return false;
4602 }
4603 if (dex_static_fields1 != dex_static_fields2) {
4604 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4605 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s", dex_static_fields1,
4606 dex_static_fields2, class_dump.c_str());
4607 return false;
4608 }
4609 if (dex_instance_fields1 != dex_instance_fields2) {
4610 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4611 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s", dex_instance_fields1,
4612 dex_instance_fields2, class_dump.c_str());
4613 return false;
4614 }
4615
4616 return true;
4617}
4618
4619// Checks whether a the super-class changed from what we had at compile-time. This would
4620// invalidate quickening.
4621static bool CheckSuperClassChange(Handle<mirror::Class> klass,
4622 const DexFile& dex_file,
4623 const DexFile::ClassDef& class_def,
4624 mirror::Class* super_class)
4625 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4626 // Check for unexpected changes in the superclass.
4627 // Quick check 1) is the super_class class-loader the boot class loader? This always has
4628 // precedence.
4629 if (super_class->GetClassLoader() != nullptr &&
4630 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
4631 // which is implied by different dex cache.
4632 klass->GetDexCache() != super_class->GetDexCache()) {
4633 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
4634 // definition for the super-class, and (b) the files are in separate oat files. The oat files
4635 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
4636 const OatFile* class_oat_file = dex_file.GetOatFile();
4637 if (class_oat_file != nullptr) {
4638 const OatFile* loaded_super_oat_file = super_class->GetDexFile().GetOatFile();
4639 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
4640 // Now check (a).
4641 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
4642 if (super_class_def != nullptr) {
4643 // Uh-oh, we found something. Do our check.
4644 std::string error_msg;
4645 if (!SimpleStructuralCheck(dex_file, *super_class_def,
4646 super_class->GetDexFile(), *super_class->GetClassDef(),
4647 &error_msg)) {
4648 // Print a warning to the log. This exception might be caught, e.g., as common in test
4649 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
4650 // only save the type of the exception.
4651 LOG(WARNING) << "Incompatible structural change detected: " <<
4652 StringPrintf(
4653 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
4654 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
4655 class_oat_file->GetLocation().c_str(),
4656 loaded_super_oat_file->GetLocation().c_str(),
4657 error_msg.c_str());
4658 ThrowIncompatibleClassChangeError(klass.Get(),
4659 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
4660 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
4661 class_oat_file->GetLocation().c_str(),
4662 loaded_super_oat_file->GetLocation().c_str(),
4663 error_msg.c_str());
4664 return false;
4665 }
4666 }
4667 }
4668 }
4669 }
4670 return true;
4671}
4672
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004673bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004674 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004675 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4676 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004677 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004678 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe35439ba2014-08-28 14:41:02 -07004679 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004680 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004681 return false;
4682 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004683 // Verify
4684 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004685 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004686 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004687 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004688 return false;
4689 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004690 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004691 klass->SetSuperClass(super_class);
Andreas Gampe15a33b32014-11-06 16:52:58 -08004692
4693 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
4694 DCHECK(Thread::Current()->IsExceptionPending());
4695 return false;
4696 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004697 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004698 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe35439ba2014-08-28 14:41:02 -07004699 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004700 for (size_t i = 0; i < interfaces->Size(); i++) {
4701 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004702 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe35439ba2014-08-28 14:41:02 -07004703 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004704 DCHECK(Thread::Current()->IsExceptionPending());
4705 return false;
4706 }
4707 // Verify
4708 if (!klass->CanAccess(interface)) {
4709 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004710 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004711 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004712 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004713 return false;
4714 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004715 }
4716 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004717 // Mark the class as loaded.
Andreas Gampe35439ba2014-08-28 14:41:02 -07004718 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004719 return true;
4720}
4721
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004722bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004723 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004724 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004725 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe35439ba2014-08-28 14:41:02 -07004726 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004727 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004728 return false;
4729 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004730 return true;
4731 }
Andreas Gampe35439ba2014-08-28 14:41:02 -07004732 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004733 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4734 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004735 return false;
4736 }
4737 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004738 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004739 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004740 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004741 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004742 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004743 return false;
4744 }
4745 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004746 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004747 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004748 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004749 return false;
4750 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004751
Brian Carlstromf3632832014-05-20 15:36:53 -07004752 // Inherit kAccClassIsFinalizable from the superclass in case this
4753 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004754 if (super->IsFinalizable()) {
4755 klass->SetFinalizable();
4756 }
4757
Elliott Hughes2da50362011-10-10 16:57:08 -07004758 // Inherit reference flags (if any) from the superclass.
4759 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4760 if (reference_flags != 0) {
4761 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4762 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004763 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004764 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004765 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004766 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004767 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004768 return false;
4769 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004770
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004771 if (kIsDebugBuild) {
4772 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe35439ba2014-08-28 14:41:02 -07004773 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004774 CHECK(super->IsResolved());
4775 super = super->GetSuperClass();
4776 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004777 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004778 return true;
4779}
4780
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004781// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004782bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07004783 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4784 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004785 if (klass->IsInterface()) {
4786 // No vtable.
4787 size_t count = klass->NumVirtualMethods();
4788 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004789 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004790 return false;
4791 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004792 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004793 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004794 }
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07004795 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4796 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004797 }
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07004798 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004799}
4800
Ian Rogers473484f2014-10-28 09:34:57 -07004801// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4802// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4803// caches in the implementation below.
4804class MethodNameAndSignatureComparator FINAL {
4805 public:
4806 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4807 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4808 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4809 name_(nullptr), name_len_(0) {
Mathieu Chartiera9ca9ac2014-10-28 18:23:02 -07004810 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4811 }
4812
4813 const char* GetName() {
4814 if (name_ == nullptr) {
4815 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4816 }
4817 return name_;
Ian Rogers473484f2014-10-28 09:34:57 -07004818 }
4819
4820 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4821 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4822 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4823 const DexFile* other_dex_file = other->GetDexFile();
4824 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4825 if (dex_file_ == other_dex_file) {
4826 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4827 }
Mathieu Chartiera9ca9ac2014-10-28 18:23:02 -07004828 GetName(); // Only used to make sure its calculated.
Ian Rogers473484f2014-10-28 09:34:57 -07004829 uint32_t other_name_len;
4830 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4831 &other_name_len);
4832 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4833 return false;
4834 }
4835 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4836 }
4837
4838 private:
4839 // Dex file for the method to compare against.
4840 const DexFile* const dex_file_;
4841 // MethodId for the method to compare against.
4842 const DexFile::MethodId* const mid_;
4843 // Lazily computed name from the dex file's strings.
4844 const char* name_;
4845 // Lazily computed name length.
4846 uint32_t name_len_;
4847};
4848
Mathieu Chartiera9ca9ac2014-10-28 18:23:02 -07004849class LinkVirtualHashTable {
4850 public:
4851 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4852 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4853 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4854 }
4855 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4856 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4857 const char* name = local_method->GetName();
Mathieu Chartier564ff982014-11-06 16:35:45 -08004858 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartiera9ca9ac2014-10-28 18:23:02 -07004859 uint32_t index = hash % hash_size_;
4860 // Linear probe until we have an empty slot.
4861 while (hash_table_[index] != invalid_index_) {
4862 if (++index == hash_size_) {
4863 index = 0;
4864 }
4865 }
4866 hash_table_[index] = virtual_method_index;
4867 }
4868 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4869 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4870 const char* name = comparator->GetName();
Mathieu Chartier564ff982014-11-06 16:35:45 -08004871 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartiera9ca9ac2014-10-28 18:23:02 -07004872 size_t index = hash % hash_size_;
4873 while (true) {
4874 const uint32_t value = hash_table_[index];
4875 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4876 // the block and can safely assume not found.
4877 if (value == invalid_index_) {
4878 break;
4879 }
4880 if (value != removed_index_) { // This signifies not already overriden.
4881 mirror::ArtMethod* virtual_method =
4882 klass_->GetVirtualMethodDuringLinking(value);
4883 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4884 hash_table_[index] = removed_index_;
4885 return value;
4886 }
4887 }
4888 if (++index == hash_size_) {
4889 index = 0;
4890 }
4891 }
4892 return GetNotFoundIndex();
4893 }
4894 static uint32_t GetNotFoundIndex() {
4895 return invalid_index_;
4896 }
4897
4898 private:
4899 static const uint32_t invalid_index_;
4900 static const uint32_t removed_index_;
4901
4902 Handle<mirror::Class> klass_;
4903 const size_t hash_size_;
4904 uint32_t* const hash_table_;
4905};
4906
4907const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4908const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4909
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004910bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07004911 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004912 if (klass->HasSuperClass()) {
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07004913 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4914 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07004915 StackHandleScope<2> hs(self);
Mingyao Yang82546342014-08-13 14:51:03 -07004916 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004917 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004918 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4919 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4920 if (UNLIKELY(vtable.Get() == nullptr)) {
4921 CHECK(self->IsExceptionPending()); // OOME.
4922 return false;
4923 }
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07004924 for (size_t i = 0; i < super_vtable_length; i++) {
4925 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004926 }
Mathieu Chartiera9ca9ac2014-10-28 18:23:02 -07004927 if (num_virtual_methods == 0) {
4928 klass->SetVTable(vtable.Get());
4929 return true;
4930 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004931 } else {
Mathieu Chartiera9ca9ac2014-10-28 18:23:02 -07004932 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4933 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4934 if (num_virtual_methods == 0) {
4935 klass->SetVTable(super_vtable);
4936 return true;
4937 }
4938 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004939 if (UNLIKELY(vtable.Get() == nullptr)) {
4940 CHECK(self->IsExceptionPending()); // OOME.
4941 return false;
4942 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004943 }
Mathieu Chartiera9ca9ac2014-10-28 18:23:02 -07004944 // How the algorithm works:
4945 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4946 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4947 // method which has not been matched to a vtable method, and j if the virtual method at the
4948 // index overrode the super virtual method at index j.
4949 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4950 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4951 // the need for the initial vtable which we later shrink back down).
4952 // 3. Add non overridden methods to the end of the vtable.
4953 static constexpr size_t kMaxStackHash = 250;
4954 const size_t hash_table_size = num_virtual_methods * 3;
4955 uint32_t* hash_table_ptr;
4956 std::unique_ptr<uint32_t[]> hash_heap_storage;
4957 if (hash_table_size <= kMaxStackHash) {
4958 hash_table_ptr = reinterpret_cast<uint32_t*>(
4959 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4960 } else {
4961 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4962 hash_table_ptr = hash_heap_storage.get();
4963 }
4964 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4965 // Add virtual methods to the hash table.
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07004966 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiera9ca9ac2014-10-28 18:23:02 -07004967 hash_table.Add(i);
4968 }
4969 // Loop through each super vtable method and see if they are overriden by a method we added to
4970 // the hash table.
4971 for (size_t j = 0; j < super_vtable_length; ++j) {
4972 // Search the hash table to see if we are overidden by any method.
4973 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4974 MethodNameAndSignatureComparator super_method_name_comparator(
4975 super_method->GetInterfaceMethodIfProxy());
4976 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4977 if (hash_index != hash_table.GetNotFoundIndex()) {
4978 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4979 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4980 super_method->GetAccessFlags())) {
4981 if (super_method->IsFinal()) {
4982 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4983 PrettyMethod(virtual_method).c_str(),
4984 super_method->GetDeclaringClassDescriptor());
4985 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004986 }
Mathieu Chartiera9ca9ac2014-10-28 18:23:02 -07004987 vtable->SetWithoutChecks<false>(j, virtual_method);
4988 virtual_method->SetMethodIndex(j);
4989 } else {
4990 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07004991 << " would have incorrectly overridden the package-private method in "
4992 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004993 }
4994 }
Mathieu Chartiera9ca9ac2014-10-28 18:23:02 -07004995 }
4996 // Add the non overridden methods at the end.
4997 size_t actual_count = super_vtable_length;
4998 for (size_t i = 0; i < num_virtual_methods; ++i) {
4999 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
5000 size_t method_idx = local_method->GetMethodIndexDuringLinking();
5001 if (method_idx < super_vtable_length &&
5002 local_method == vtable->GetWithoutChecks(method_idx)) {
5003 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005004 }
Mathieu Chartiera9ca9ac2014-10-28 18:23:02 -07005005 vtable->SetWithoutChecks<false>(actual_count, local_method);
5006 local_method->SetMethodIndex(actual_count);
5007 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005008 }
5009 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005010 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005011 return false;
5012 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005013 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005014 CHECK_LE(actual_count, max_count);
5015 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005016 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe35439ba2014-08-28 14:41:02 -07005017 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005018 CHECK(self->IsExceptionPending()); // OOME.
5019 return false;
5020 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005021 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005022 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005023 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005024 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07005025 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005026 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
5027 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005028 return false;
5029 }
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005030 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
5031 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005032 CHECK(self->IsExceptionPending()); // OOME.
5033 return false;
5034 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07005035 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005036 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005037 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005038 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005039 }
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005040 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005041 }
5042 return true;
5043}
5044
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005045bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
5046 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
5047 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartier7989d222014-10-27 17:30:20 -07005048 StackHandleScope<2> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005049 Runtime* const runtime = Runtime::Current();
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005050 const bool has_superclass = klass->HasSuperClass();
5051 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
5052 const bool have_interfaces = interfaces.Get() != nullptr;
5053 const size_t num_interfaces =
5054 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
5055 if (num_interfaces == 0) {
5056 if (super_ifcount == 0) {
5057 // Class implements no interfaces.
5058 DCHECK_EQ(klass->GetIfTableCount(), 0);
5059 DCHECK(klass->GetIfTable() == nullptr);
5060 return true;
5061 }
Ian Rogers9bc81912012-10-11 21:43:36 -07005062 // Class implements same interfaces as parent, are any of these not marker interfaces?
5063 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005064 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005065 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005066 if (super_iftable->GetMethodArrayCount(i) > 0) {
5067 has_non_marker_interface = true;
5068 break;
5069 }
5070 }
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005071 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07005072 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005073 klass->SetIfTable(super_iftable);
5074 return true;
5075 }
5076 }
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005077 size_t ifcount = super_ifcount + num_interfaces;
5078 for (size_t i = 0; i < num_interfaces; i++) {
5079 mirror::Class* interface = have_interfaces ?
5080 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
5081 DCHECK(interface != nullptr);
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005082 if (UNLIKELY(!interface->IsInterface())) {
5083 std::string temp;
5084 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
5085 PrettyDescriptor(klass.Get()).c_str(),
5086 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
5087 return false;
5088 }
5089 ifcount += interface->GetIfTableCount();
5090 }
Mathieu Chartier7989d222014-10-27 17:30:20 -07005091 Handle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe35439ba2014-08-28 14:41:02 -07005092 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005093 CHECK(self->IsExceptionPending()); // OOME.
5094 return false;
5095 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005096 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005097 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005098 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005099 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07005100 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005101 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005102 }
5103 // Flatten the interface inheritance hierarchy.
5104 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005105 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier7989d222014-10-27 17:30:20 -07005106 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
5107 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005108 // Check if interface is already in iftable
5109 bool duplicate = false;
5110 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005111 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005112 if (existing_interface == interface) {
5113 duplicate = true;
5114 break;
5115 }
5116 }
5117 if (!duplicate) {
5118 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07005119 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005120 // Add this interface's non-duplicate super-interfaces.
5121 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005122 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005123 bool super_duplicate = false;
5124 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005125 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005126 if (existing_interface == super_interface) {
5127 super_duplicate = true;
5128 break;
5129 }
5130 }
5131 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005132 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005133 }
5134 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005135 }
5136 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08005137 // Shrink iftable in case duplicates were found
5138 if (idx < ifcount) {
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005139 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005140 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe35439ba2014-08-28 14:41:02 -07005141 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005142 CHECK(self->IsExceptionPending()); // OOME.
5143 return false;
5144 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08005145 ifcount = idx;
5146 } else {
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005147 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005148 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005149 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07005150 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07005151 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005152 return true;
5153 }
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005154 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
5155 hs.NewHandle(klass->GetVTableDuringLinking()));
Brian Carlstromea46f952013-07-30 01:26:50 -07005156 std::vector<mirror::ArtMethod*> miranda_list;
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005157 // Copy the IMT from the super class if possible.
5158 bool extend_super_iftable = false;
5159 if (has_superclass) {
5160 mirror::Class* super_class = klass->GetSuperClass();
5161 extend_super_iftable = true;
5162 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
5163 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
5164 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
5165 }
5166 } else {
5167 // No imt in the super class, need to reconstruct from the iftable.
5168 mirror::IfTable* if_table = super_class->GetIfTable();
5169 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5170 const size_t length = super_class->GetIfTableCount();
5171 for (size_t i = 0; i < length; ++i) {
5172 mirror::Class* interface = iftable->GetInterface(i);
5173 const size_t num_virtuals = interface->NumVirtualMethods();
5174 const size_t method_array_count = if_table->GetMethodArrayCount(i);
5175 DCHECK_EQ(num_virtuals, method_array_count);
5176 if (method_array_count == 0) {
5177 continue;
5178 }
5179 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
5180 for (size_t j = 0; j < num_virtuals; ++j) {
5181 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
5182 if (method->IsMiranda()) {
5183 continue;
5184 }
5185 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
5186 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5187 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5188 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5189 out_imt->SetReference(imt_index, method);
5190 } else if (imt_ref != conflict_method) {
5191 out_imt->SetReference(imt_index, conflict_method);
5192 }
5193 }
5194 }
5195 }
5196 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005197 for (size_t i = 0; i < ifcount; ++i) {
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005198 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07005199 if (num_methods > 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005200 StackHandleScope<2> hs(self);
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005201 const bool is_super = i < super_ifcount;
5202 const bool super_interface = is_super && extend_super_iftable;
5203 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
5204 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
5205 if (super_interface) {
5206 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
5207 DCHECK(if_table != nullptr);
5208 DCHECK(if_table->GetMethodArray(i) != nullptr);
5209 // If we are working on a super interface, try extending the existing method array.
5210 method_array = hs.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
5211 AsObjectArray<mirror::ArtMethod>());
5212 // We are overwriting a super class interface, try to only virtual methods instead of the
5213 // whole vtable.
5214 input_array = hs.NewHandle(klass->GetVirtualMethods());
5215 } else {
5216 method_array = hs.NewHandle(AllocArtMethodArray(self, num_methods));
5217 // A new interface, we need the whole vtable incase a new interface method is implemented
5218 // in the whole superclass.
5219 input_array = vtable;
5220 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005221 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005222 CHECK(self->IsExceptionPending()); // OOME.
5223 return false;
5224 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005225 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005226 if (input_array.Get() == nullptr) {
5227 // If the added virtual methods is empty, do nothing.
5228 DCHECK(super_interface);
5229 continue;
5230 }
Ian Rogers62d6c772013-02-27 08:32:07 -08005231 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005232 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartiera9ca9ac2014-10-28 18:23:02 -07005233 MethodNameAndSignatureComparator interface_name_comparator(
5234 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07005235 int32_t k;
5236 // For each method listed in the interface's method list, find the
5237 // matching method in our class's method list. We want to favor the
5238 // subclass over the superclass, which just requires walking
5239 // back from the end of the vtable. (This only matters if the
5240 // superclass defines a private method and this class redefines
5241 // it -- otherwise it would use the same vtable slot. In .dex files
5242 // those don't end up in the virtual method table, so it shouldn't
5243 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005244 for (k = input_array->GetLength() - 1; k >= 0; --k) {
5245 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers473484f2014-10-28 09:34:57 -07005246 mirror::ArtMethod* vtable_method_for_name_comparison =
5247 vtable_method->GetInterfaceMethodIfProxy();
5248 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartiera9ca9ac2014-10-28 18:23:02 -07005249 vtable_method_for_name_comparison)) {
Elliott Hughes68243612013-02-22 17:16:07 -08005250 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005251 ThrowIllegalAccessError(
5252 klass.Get(),
5253 "Method '%s' implementing interface method '%s' is not public",
5254 PrettyMethod(vtable_method).c_str(),
5255 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07005256 return false;
5257 }
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005258 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07005259 // Place method in imt if entry is empty, place conflict otherwise.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005260 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005261 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5262 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5263 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5264 out_imt->SetReference(imt_index, vtable_method);
5265 } else if (imt_ref != conflict_method) {
5266 // If we are not a conflict and we have the same signature and name as the imt entry,
5267 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartiera9ca9ac2014-10-28 18:23:02 -07005268 MethodNameAndSignatureComparator imt_ref_name_comparator(
5269 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers473484f2014-10-28 09:34:57 -07005270 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartiera9ca9ac2014-10-28 18:23:02 -07005271 vtable_method_for_name_comparison)) {
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005272 out_imt->SetReference(imt_index, vtable_method);
5273 } else {
5274 out_imt->SetReference(imt_index, conflict_method);
5275 }
Jeff Hao88474b42013-10-23 16:24:40 -07005276 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005277 break;
5278 }
5279 }
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005280 if (k < 0 && !super_interface) {
5281 mirror::ArtMethod* miranda_method = nullptr;
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07005282 for (mirror::ArtMethod* mir_method : miranda_list) {
Mathieu Chartiera9ca9ac2014-10-28 18:23:02 -07005283 if (interface_name_comparator.HasSameNameAndSignature(
5284 mir_method->GetInterfaceMethodIfProxy())) {
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005285 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07005286 break;
5287 }
5288 }
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005289 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005290 // Point the interface table at a phantom slot.
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005291 miranda_method = down_cast<mirror::ArtMethod*>(interface_method->Clone(self));
5292 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005293 CHECK(self->IsExceptionPending()); // OOME.
5294 return false;
5295 }
Ian Rogersa436fde2013-08-27 23:34:06 -07005296 // TODO: If a methods move then the miranda_list may hold stale references.
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005297 miranda_list.push_back(miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07005298 }
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005299 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005300 }
5301 }
5302 }
5303 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005304 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07005305 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07005306 int new_method_count = old_method_count + miranda_list.size();
Ian Rogersa436fde2013-08-27 23:34:06 -07005307 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
5308 if (old_method_count == 0) {
5309 virtuals = AllocArtMethodArray(self, new_method_count);
5310 } else {
5311 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
5312 }
Andreas Gampe35439ba2014-08-28 14:41:02 -07005313 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005314 CHECK(self->IsExceptionPending()); // OOME.
5315 return false;
5316 }
5317 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005318
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005319 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07005320 int new_vtable_count = old_vtable_count + miranda_list.size();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005321 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe35439ba2014-08-28 14:41:02 -07005322 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005323 CHECK(self->IsExceptionPending()); // OOME.
5324 return false;
5325 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005326 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005327 mirror::ArtMethod* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07005328 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07005329 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
5330 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
5331 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005332 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005333 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005334 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005335 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005336 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005337
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07005338 if (kIsDebugBuild) {
5339 mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking();
5340 for (int i = 0; i < vtable->GetLength(); ++i) {
5341 CHECK(vtable->GetWithoutChecks(i) != nullptr);
5342 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005343 }
5344
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005345 return true;
5346}
5347
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005348bool ClassLinker::LinkInstanceFields(Handle<mirror::Class> klass) {
Andreas Gampe35439ba2014-08-28 14:41:02 -07005349 CHECK(klass.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005350 return LinkFields(klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005351}
5352
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005353bool ClassLinker::LinkStaticFields(Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe35439ba2014-08-28 14:41:02 -07005354 CHECK(klass.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005355 return LinkFields(klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005356}
5357
Brian Carlstromdbc05252011-09-09 01:59:59 -07005358struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005359 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5360 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005361 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005362 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005363 NO_THREAD_SAFETY_ANALYSIS {
Brian Carlstromdbc05252011-09-09 01:59:59 -07005364 // First come reference fields, then 64-bit, and finally 32-bit
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005365 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5366 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005367 if (type1 != type2) {
Vladimir Marko938f9662014-11-12 17:02:02 +00005368 if (type1 == Primitive::kPrimNot) {
5369 // Reference always goes first.
5370 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08005371 }
Vladimir Marko938f9662014-11-12 17:02:02 +00005372 if (type2 == Primitive::kPrimNot) {
5373 // Reference always goes first.
5374 return false;
5375 }
5376 size_t size1 = Primitive::ComponentSize(type1);
5377 size_t size2 = Primitive::ComponentSize(type2);
5378 if (size1 != size2) {
5379 // Larger primitive types go first.
5380 return size1 > size2;
5381 }
5382 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
5383 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005384 }
Vladimir Markob34674d2014-11-17 15:13:34 +00005385 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
5386 // by name and for equal names by type id index.
5387 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
5388 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07005389 }
5390};
5391
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005392bool ClassLinker::LinkFields(Handle<mirror::Class> klass, bool is_static, size_t* class_size) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005393 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005394 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005395
Brian Carlstromea46f952013-07-30 01:26:50 -07005396 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005397 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005398
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005399 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005400 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005401 if (is_static) {
Vladimir Markobfa3ed02014-11-10 18:32:59 +00005402 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005403 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005404 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe35439ba2014-08-28 14:41:02 -07005405 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005406 CHECK(super_class->IsResolved())
5407 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005408 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005409 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005410 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005411
Andreas Gampe35439ba2014-08-28 14:41:02 -07005412 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005413
Brian Carlstromdbc05252011-09-09 01:59:59 -07005414 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005415 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005416 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005417 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005418 mirror::ArtField* f = fields->Get(i);
Andreas Gampe35439ba2014-08-28 14:41:02 -07005419 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005420 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005421 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005422 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5423 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005424
5425 // References should be at the front.
5426 size_t current_field = 0;
5427 size_t num_reference_fields = 0;
5428 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005429 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005430 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005431 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005432 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005433 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005434 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005435 grouped_and_sorted_fields.pop_front();
5436 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005437 field->SetOffset(field_offset);
Vladimir Markobfa3ed02014-11-10 18:32:59 +00005438 field_offset = MemberOffset(field_offset.Uint32Value() +
5439 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005440 }
5441
5442 // Now we want to pack all of the double-wide fields together. If
5443 // we're not aligned, though, we want to shuffle one 32-bit field
5444 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07005445 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07005446 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005447 mirror::ArtField* field = grouped_and_sorted_fields[i];
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005448 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstromf3632832014-05-20 15:36:53 -07005449 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005450 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07005451 continue;
5452 }
Vladimir Markobfa3ed02014-11-10 18:32:59 +00005453 current_field++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005454 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005455 // drop the consumed field
5456 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
5457 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005458 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005459 // whether we found a 32-bit field for padding or not, we advance
Vladimir Markobfa3ed02014-11-10 18:32:59 +00005460 field_offset = MemberOffset(field_offset.Uint32Value() +
5461 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005462 }
5463
5464 // Alignment is good, shuffle any double-wide fields forward, and
5465 // finish assigning field offsets to all fields.
Brian Carlstromf3632832014-05-20 15:36:53 -07005466 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()))
5467 << PrettyClass(klass.Get());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005468 while (!grouped_and_sorted_fields.empty()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005469 mirror::ArtField* field = grouped_and_sorted_fields.front();
Brian Carlstromdbc05252011-09-09 01:59:59 -07005470 grouped_and_sorted_fields.pop_front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005471 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstromf3632832014-05-20 15:36:53 -07005472 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005473 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005474 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005475 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07005476 ? sizeof(uint64_t)
5477 : sizeof(uint32_t)));
5478 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005479 }
5480
Elliott Hughesadb460d2011-10-05 17:02:34 -07005481 // 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 -07005482 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005483 // We know there are no non-reference fields in the Reference classes, and we know
5484 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005485 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005486 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005487 --num_reference_fields;
5488 }
5489
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005490 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005491 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005492 if (is_static) {
5493 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005494 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005495 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005496 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005497 if (!klass->IsVariableSize()) {
Mathieu Chartiere832e642014-11-10 11:08:06 -08005498 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
5499 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(sizeof(void*)));
5500 } else {
5501 std::string temp;
5502 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
5503 size_t previous_size = klass->GetObjectSize();
5504 if (previous_size != 0) {
5505 // Make sure that we didn't originally have an incorrect size.
5506 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
5507 }
5508 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005509 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005510 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005511 }
Vladimir Markobfa3ed02014-11-10 18:32:59 +00005512
5513 if (kIsDebugBuild) {
5514 // Make sure that the fields array is ordered by name but all reference
5515 // offsets are at the beginning as far as alignment allows.
5516 MemberOffset start_ref_offset = is_static
5517 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
5518 : klass->GetFirstReferenceInstanceFieldOffset();
5519 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
5520 num_reference_fields *
5521 sizeof(mirror::HeapReference<mirror::Object>));
5522 MemberOffset current_ref_offset = start_ref_offset;
5523 for (size_t i = 0; i < num_fields; i++) {
5524 mirror::ArtField* field = fields->Get(i);
5525 if (false) { // enable to debug field layout
5526 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
5527 << " class=" << PrettyClass(klass.Get())
5528 << " field=" << PrettyField(field)
5529 << " offset="
5530 << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset()));
5531 }
5532 if (i != 0) {
5533 mirror::ArtField* prev_field = fields->Get(i - 1u);
Vladimir Markob34674d2014-11-17 15:13:34 +00005534 // NOTE: The field names can be the same. This is not possible in the Java language
5535 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
5536 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Markobfa3ed02014-11-10 18:32:59 +00005537 }
5538 Primitive::Type type = field->GetTypeAsPrimitiveType();
5539 bool is_primitive = type != Primitive::kPrimNot;
5540 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
5541 strcmp("referent", field->GetName()) == 0) {
5542 is_primitive = true; // We lied above, so we have to expect a lie here.
5543 }
5544 MemberOffset offset = field->GetOffsetDuringLinking();
5545 if (is_primitive) {
5546 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
5547 // Shuffled before references.
5548 size_t type_size = Primitive::ComponentSize(type);
5549 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
5550 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
5551 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
5552 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
5553 }
5554 } else {
5555 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
5556 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
5557 sizeof(mirror::HeapReference<mirror::Object>));
5558 }
5559 }
5560 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
5561 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005562 return true;
5563}
5564
Vladimir Markobfa3ed02014-11-10 18:32:59 +00005565// Set the bitmap of reference instance field offsets.
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005566void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005567 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005568 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe35439ba2014-08-28 14:41:02 -07005569 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005570 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07005571 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005572 if (reference_offsets == CLASS_WALK_SUPER) {
5573 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005574 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005575 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005576 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005577 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005578}
5579
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005580void ClassLinker::CreateReferenceStaticOffsets(Handle<mirror::Class> klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005581 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005582}
5583
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005584void ClassLinker::CreateReferenceOffsets(Handle<mirror::Class> klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005585 uint32_t reference_offsets) {
5586 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005587 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
5588 : klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Markobfa3ed02014-11-10 18:32:59 +00005589 if (num_reference_fields != 0u) {
5590 // All of the fields that contain object references are guaranteed be grouped in memory
5591 // starting at an appropriately aligned address after super class object data for instances
5592 // and after the basic class data for classes.
5593 uint32_t start_offset =
5594 !is_static
5595 ? klass->GetFirstReferenceInstanceFieldOffset().Uint32Value()
5596 // Can't use klass->GetFirstReferenceStaticFieldOffset() yet.
5597 : klass->ShouldHaveEmbeddedImtAndVTable()
5598 ? mirror::Class::ComputeClassSize(
5599 true, klass->GetVTableDuringLinking()->GetLength(), 0, 0, 0)
5600 : sizeof(mirror::Class);
5601 uint32_t start_bit = start_offset / sizeof(mirror::HeapReference<mirror::Object>);
5602 if (start_bit + num_reference_fields > 32) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005603 reference_offsets = CLASS_WALK_SUPER;
Vladimir Markobfa3ed02014-11-10 18:32:59 +00005604 } else {
5605 reference_offsets |= (0xffffffffu >> start_bit) &
5606 (0xffffffffu << (32 - (start_bit + num_reference_fields)));
Brian Carlstrom4873d462011-08-21 15:23:39 -07005607 }
5608 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005609 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005610 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005611 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005612 } else {
5613 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005614 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005615}
5616
Mathieu Chartier590fee92013-09-13 13:46:47 -07005617mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005618 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005619 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005620 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe35439ba2014-08-28 14:41:02 -07005621 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005622 return resolved;
5623 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005624 uint32_t utf16_length;
5625 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005626 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005627 dex_cache->SetResolvedString(string_idx, string);
5628 return string;
5629}
5630
Mathieu Chartier590fee92013-09-13 13:46:47 -07005631mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005632 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005633 StackHandleScope<2> hs(Thread::Current());
5634 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5635 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005636 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5637}
5638
5639mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005640 Handle<mirror::DexCache> dex_cache,
5641 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe35439ba2014-08-28 14:41:02 -07005642 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005643 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe35439ba2014-08-28 14:41:02 -07005644 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005645 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005646 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005647 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe35439ba2014-08-28 14:41:02 -07005648 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005649 // TODO: we used to throw here if resolved's class loader was not the
5650 // boot class loader. This was to permit different classes with the
5651 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005652 dex_cache->SetResolvedType(type_idx, resolved);
5653 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005654 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005655 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005656 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005657 StackHandleScope<1> hs(self);
5658 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005659 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe35439ba2014-08-28 14:41:02 -07005660 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005661 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005662 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe35439ba2014-08-28 14:41:02 -07005663 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005664 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005665 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005666 }
Andreas Gampe35439ba2014-08-28 14:41:02 -07005667 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005668 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005669 return resolved;
5670}
5671
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005672mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
5673 Handle<mirror::DexCache> dex_cache,
5674 Handle<mirror::ClassLoader> class_loader,
5675 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005676 InvokeType type) {
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005677 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005678 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005679 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005680 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005681 return resolved;
5682 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005683 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005684 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005685 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005686 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005687 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005688 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005689 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005690 // Scan using method_idx, this saves string compares but will only hit for matching dex
5691 // caches/files.
5692 switch (type) {
5693 case kDirect: // Fall-through.
5694 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005695 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005696 break;
5697 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005698 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005699 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005700 break;
5701 case kSuper: // Fall-through.
5702 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005703 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005704 break;
5705 default:
5706 LOG(FATAL) << "Unreachable - invocation type: " << type;
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005707 }
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005708 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005709 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005710 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005711 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005712 switch (type) {
5713 case kDirect: // Fall-through.
5714 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005715 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005716 break;
5717 case kInterface:
5718 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005719 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005720 break;
5721 case kSuper: // Fall-through.
5722 case kVirtual:
5723 resolved = klass->FindVirtualMethod(name, signature);
5724 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005725 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005726 }
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005727 // If we found a method, check for incompatible class changes.
5728 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005729 // Be a good citizen and update the dex cache to speed subsequent calls.
5730 dex_cache->SetResolvedMethod(method_idx, resolved);
5731 return resolved;
5732 } else {
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005733 // If we had a method, it's an incompatible-class-change error.
5734 if (resolved != nullptr) {
5735 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5736 } else {
5737 // We failed to find the method which means either an access error, an incompatible class
5738 // change, or no such method. First try to find the method among direct and virtual methods.
5739 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5740 const Signature signature = dex_file.GetMethodSignature(method_id);
5741 switch (type) {
5742 case kDirect:
5743 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005744 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005745 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5746 // have had a resolved method before, which triggers the "true" branch above.
5747 break;
5748 case kInterface:
5749 case kVirtual:
5750 case kSuper:
5751 resolved = klass->FindDirectMethod(name, signature);
5752 break;
5753 }
5754
5755 // If we found something, check that it can be accessed by the referrer.
5756 if (resolved != nullptr && referrer.Get() != nullptr) {
5757 mirror::Class* methods_class = resolved->GetDeclaringClass();
5758 mirror::Class* referring_class = referrer->GetDeclaringClass();
5759 if (!referring_class->CanAccess(methods_class)) {
5760 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5761 resolved, type);
5762 return nullptr;
5763 } else if (!referring_class->CanAccessMember(methods_class,
5764 resolved->GetAccessFlags())) {
5765 ThrowIllegalAccessErrorMethod(referring_class, resolved);
5766 return nullptr;
5767 }
5768 }
5769
5770 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
5771 // methods and throw if we find the method there. If we find nothing, throw a
5772 // NoSuchMethodError.
5773 switch (type) {
5774 case kDirect:
5775 case kStatic:
5776 if (resolved != nullptr) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005777 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005778 } else {
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005779 resolved = klass->FindInterfaceMethod(name, signature);
5780 if (resolved != nullptr) {
5781 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5782 } else {
5783 ThrowNoSuchMethodError(type, klass, name, signature);
5784 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005785 }
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005786 break;
5787 case kInterface:
5788 if (resolved != nullptr) {
5789 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005790 } else {
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005791 resolved = klass->FindVirtualMethod(name, signature);
5792 if (resolved != nullptr) {
5793 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5794 } else {
5795 ThrowNoSuchMethodError(type, klass, name, signature);
5796 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005797 }
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005798 break;
5799 case kSuper:
Andreas Gampe9cb8d7a2014-08-25 20:55:01 -07005800 if (resolved != nullptr) {
5801 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5802 } else {
5803 ThrowNoSuchMethodError(type, klass, name, signature);
5804 }
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005805 break;
5806 case kVirtual:
5807 if (resolved != nullptr) {
5808 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5809 } else {
5810 resolved = klass->FindInterfaceMethod(name, signature);
5811 if (resolved != nullptr) {
5812 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5813 } else {
5814 ThrowNoSuchMethodError(type, klass, name, signature);
5815 }
5816 }
5817 break;
5818 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005819 }
5820 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeb5d1efa2014-08-13 21:49:37 -07005821 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005822 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005823}
5824
Mathieu Chartier590fee92013-09-13 13:46:47 -07005825mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005826 Handle<mirror::DexCache> dex_cache,
5827 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005828 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005829 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005830 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005831 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005832 return resolved;
5833 }
5834 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005835 Thread* const self = Thread::Current();
5836 StackHandleScope<1> hs(self);
5837 Handle<mirror::Class> klass(
5838 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005839 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005840 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005841 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005842 }
5843
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005844 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005845 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005846 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005847 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005848 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005849
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005850 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005851 const char* name = dex_file.GetFieldName(field_id);
5852 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5853 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005854 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005855 } else {
5856 resolved = klass->FindInstanceField(name, type);
5857 }
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005858 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005859 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe35439ba2014-08-28 14:41:02 -07005860 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005861 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005862 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005863 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005864 return resolved;
5865}
5866
Brian Carlstromea46f952013-07-30 01:26:50 -07005867mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005868 uint32_t field_idx,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005869 Handle<mirror::DexCache> dex_cache,
5870 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005871 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005872 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe4ef12f52014-07-31 16:23:49 -07005873 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005874 return resolved;
5875 }
5876 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005877 Thread* self = Thread::Current();
5878 StackHandleScope<1> hs(self);
5879 Handle<mirror::Class> klass(
5880 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe35439ba2014-08-28 14:41:02 -07005881 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005882 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe35439ba2014-08-28 14:41:02 -07005883 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005884 }
5885
Ian Rogersdfb325e2013-10-30 01:00:44 -07005886 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5887 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005888 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005889 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe35439ba2014-08-28 14:41:02 -07005890 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005891 dex_cache->SetResolvedField(field_idx, resolved);
5892 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005893 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005894 }
5895 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005896}
5897
Brian Carlstromea46f952013-07-30 01:26:50 -07005898const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005899 uint32_t* length) {
5900 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5901 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005902 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005903 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005904 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005905}
5906
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005907void ClassLinker::DumpAllClasses(int flags) {
5908 if (dex_cache_image_class_lookup_required_) {
5909 MoveImageClassesToClassTable();
5910 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005911 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5912 // 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 -08005913 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005914 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005915 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08005916 for (GcRoot<mirror::Class>& it : class_table_) {
5917 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005918 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005919 }
5920
5921 for (size_t i = 0; i < all_classes.size(); ++i) {
5922 all_classes[i]->DumpClass(std::cerr, flags);
5923 }
5924}
5925
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005926void ClassLinker::DumpForSigQuit(std::ostream& os) {
5927 if (dex_cache_image_class_lookup_required_) {
5928 MoveImageClassesToClassTable();
5929 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005930 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08005931 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5932 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005933}
5934
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005935size_t ClassLinker::NumLoadedClasses() {
5936 if (dex_cache_image_class_lookup_required_) {
5937 MoveImageClassesToClassTable();
5938 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005939 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08005940 // Only return non zygote classes since these are the ones which apps which care about.
5941 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005942}
5943
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005944pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005945 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005946}
5947
5948pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005949 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005950}
5951
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005952void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005953 DCHECK(!init_done_);
5954
Andreas Gampe35439ba2014-08-28 14:41:02 -07005955 DCHECK(klass != nullptr);
5956 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005957
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005958 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe35439ba2014-08-28 14:41:02 -07005959 DCHECK(class_roots != nullptr);
5960 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005961 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005962}
5963
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08005964std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5965 const {
5966 std::string temp;
Mathieu Chartier564ff982014-11-06 16:35:45 -08005967 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08005968}
5969
5970bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5971 const GcRoot<mirror::Class>& b) {
5972 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5973 return false;
5974 }
5975 std::string temp;
5976 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5977}
5978
5979std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5980 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartier564ff982014-11-06 16:35:45 -08005981 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08005982}
5983
5984bool ClassLinker::ClassDescriptorHashEquals::operator()(
5985 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) {
5986 if (a.Read()->GetClassLoader() != b.second) {
5987 return false;
5988 }
5989 return a.Read()->DescriptorEquals(b.first);
5990}
5991
5992bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5993 const char* descriptor) {
5994 return a.Read()->DescriptorEquals(descriptor);
5995}
5996
5997std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartier564ff982014-11-06 16:35:45 -08005998 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartiere05d1d52014-11-03 11:41:47 -08005999}
6000
Sebastien Hertz7f418db2014-11-26 22:11:27 +01006001bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
6002 // Non-image methods don't use direct code pointer.
6003 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
6004 return false;
6005 }
6006 if (m->IsPrivate()) {
6007 // The method can only be called inside its own oat file. Therefore it won't be called using
6008 // its direct code if the oat file has been compiled in PIC mode.
6009 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
6010 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
6011 const OatFile::OatDexFile* oat_dex_file = class_linker->FindOpenedOatDexFileForDexFile(dex_file);
6012 if (oat_dex_file == nullptr) {
6013 // No oat file: the method has not been compiled.
6014 return false;
6015 }
6016 const OatFile* oat_file = oat_dex_file->GetOatFile();
6017 return oat_file != nullptr && !oat_file->IsPic();
6018 } else {
6019 // The method can be called outside its own oat file. Therefore it won't be called using its
6020 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
6021 ReaderMutexLock mu(Thread::Current(), dex_lock_);
6022 for (const OatFile* oat_file : oat_files_) {
6023 if (!oat_file->IsPic()) {
6024 return true;
6025 }
6026 }
6027 return false;
6028 }
6029}
6030
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006031} // namespace art