blob: 2e1f364c55789b34b166b70b3841ffe0d46dab09 [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
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070019#include <unistd.h>
20
Alex Lighteb7c1442015-08-31 13:17:42 -070021#include <algorithm>
Brian Carlstromdbc05252011-09-09 01:59:59 -070022#include <deque>
Ian Rogerscf7f1912014-10-22 22:06:39 -070023#include <iostream>
Vladimir Marko21300532017-01-24 18:06:55 +000024#include <map>
Ian Rogers700a4022014-05-19 16:49:03 -070025#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070026#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070027#include <string>
Andreas Gampe9f3928f2019-02-04 11:19:31 -080028#include <string_view>
Alex Lighteb7c1442015-08-31 13:17:42 -070029#include <tuple>
Alex Lighteb7c1442015-08-31 13:17:42 -070030#include <unordered_map>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070031#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070032#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070033
Andreas Gampe46ee31b2016-12-14 10:11:49 -080034#include "android-base/stringprintf.h"
35
Mathieu Chartierc7853442015-03-27 14:35:38 -070036#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070037#include "art_method-inl.h"
38#include "base/arena_allocator.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080039#include "base/casts.h"
David Sehr67bf42e2018-02-26 16:43:04 -080040#include "base/leb128.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080041#include "base/logging.h"
David Sehrc431b9d2018-03-02 12:01:51 -080042#include "base/os.h"
43#include "base/quasi_atomic.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070044#include "base/scoped_arena_containers.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010045#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080046#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080047#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010048#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080049#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080050#include "base/utils.h"
Andreas Gampeb9aec2c2015-04-23 22:23:47 -070051#include "base/value_object.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070052#include "cha.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080053#include "class_linker-inl.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070054#include "class_loader_utils.h"
Vladimir Markob4eb1b12018-05-24 11:09:38 +010055#include "class_root.h"
Mathieu Chartiere4275c02015-08-06 15:34:15 -070056#include "class_table-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000057#include "compiler_callbacks.h"
Vladimir Marko606adb32018-04-05 14:49:24 +010058#include "debug_print.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080059#include "debugger.h"
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -070060#include "dex/class_accessor-inl.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080061#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080062#include "dex/dex_file-inl.h"
63#include "dex/dex_file_exception_helpers.h"
64#include "dex/dex_file_loader.h"
Andreas Gampead1aa632019-01-02 10:30:54 -080065#include "dex/signature-inl.h"
David Sehr0225f8e2018-01-31 08:52:24 +000066#include "dex/utf.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070067#include "entrypoints/entrypoint_utils.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070068#include "entrypoints/runtime_asm_entrypoints.h"
Alex Light705ad492015-09-21 11:36:30 -070069#include "experimental_flags.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070070#include "gc/accounting/card_table-inl.h"
Mathieu Chartier03c1dd92016-03-07 16:13:54 -080071#include "gc/accounting/heap_bitmap-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +000072#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070073#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070074#include "gc/heap.h"
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -070075#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070076#include "gc/space/image_space.h"
Vladimir Marko8d6768d2017-03-14 10:13:21 +000077#include "gc/space/space-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070078#include "gc_root-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070079#include "handle_scope-inl.h"
Andreas Gampeaa120012018-03-28 16:23:24 -070080#include "hidden_api.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080081#include "image-inl.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070082#include "imt_conflict_table.h"
83#include "imtable-inl.h"
Mathieu Chartier74ccee62018-10-10 10:30:29 -070084#include "intern_table-inl.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070085#include "interpreter/interpreter.h"
David Srbeckyfb3de3d2018-01-29 16:11:49 +000086#include "jit/debugger_interface.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080087#include "jit/jit.h"
88#include "jit/jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010089#include "jni/java_vm_ext.h"
90#include "jni/jni_internal.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070091#include "linear_alloc.h"
Andreas Gampe8e0f0432018-10-24 13:38:03 -070092#include "mirror/array-alloc-inl.h"
93#include "mirror/array-inl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +000094#include "mirror/call_site.h"
Andreas Gampe70f5fd02018-10-24 19:58:37 -070095#include "mirror/class-alloc-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080096#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070097#include "mirror/class.h"
Alex Lightd6251582016-10-31 11:12:30 -070098#include "mirror/class_ext.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080099#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -0700100#include "mirror/dex_cache-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700101#include "mirror/dex_cache.h"
Narayan Kamath000e1882016-10-24 17:14:25 +0100102#include "mirror/emulated_stack_frame.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700103#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800104#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700105#include "mirror/method.h"
Narayan Kamathafa48272016-08-03 12:46:58 +0100106#include "mirror/method_handle_impl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +0000107#include "mirror/method_handles_lookup.h"
Steven Morelande431e272017-07-18 16:53:49 -0700108#include "mirror/method_type.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800109#include "mirror/object-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +0000110#include "mirror/object-refvisitor-inl.h"
Andreas Gampe52ecb652018-10-24 15:18:21 -0700111#include "mirror/object_array-alloc-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700112#include "mirror/object_array-inl.h"
Chris Wailes0c61be42018-09-26 17:27:34 -0700113#include "mirror/object_reference.h"
114#include "mirror/object_reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800115#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -0700116#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800117#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700118#include "mirror/string-inl.h"
Orion Hodson005ac512017-10-24 15:43:43 +0100119#include "mirror/var_handle.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700120#include "native/dalvik_system_DexFile.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -0700121#include "nativehelper/scoped_local_ref.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700122#include "oat.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700123#include "oat_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700124#include "oat_file.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700125#include "oat_file_assistant.h"
126#include "oat_file_manager.h"
127#include "object_lock.h"
David Sehr82d046e2018-04-23 08:14:19 -0700128#include "profile/profile_compilation_info.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700129#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800130#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700131#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700132#include "thread-inl.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700133#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700134#include "trace.h"
Vladimir Marko05792b92015-08-03 11:56:49 +0100135#include "utils/dex_cache_arrays_layout-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800136#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700137#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700138
139namespace art {
140
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800141using android::base::StringPrintf;
142
Mathieu Chartierc7853442015-03-27 14:35:38 -0700143static constexpr bool kSanityCheckObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700144static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700145
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700146static void ThrowNoClassDefFoundError(const char* fmt, ...)
147 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700148 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700149static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700150 va_list args;
151 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800152 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000153 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800154 va_end(args);
155}
156
Andreas Gampe99babb62015-11-02 16:20:00 -0800157static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700158 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700159 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700160 StackHandleScope<1> hs(self);
161 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700162 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700163 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700164
165 if (exception_class == nullptr) {
166 // No exc class ~ no <init>-with-string.
167 CHECK(self->IsExceptionPending());
168 self->ClearException();
169 return false;
170 }
171
Vladimir Markoba118822017-06-12 15:41:56 +0100172 ArtMethod* exception_init_method = exception_class->FindConstructor(
173 "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700174 return exception_init_method != nullptr;
175}
176
Alex Lightd6251582016-10-31 11:12:30 -0700177static mirror::Object* GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700178 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700179 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
180 if (ext == nullptr) {
181 return nullptr;
182 } else {
183 return ext->GetVerifyError();
184 }
185}
186
187// Helper for ThrowEarlierClassFailure. Throws the stored error.
188static void HandleEarlierVerifyError(Thread* self,
189 ClassLinker* class_linker,
190 ObjPtr<mirror::Class> c)
191 REQUIRES_SHARED(Locks::mutator_lock_) {
192 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800193 DCHECK(obj != nullptr);
194 self->AssertNoPendingException();
195 if (obj->IsClass()) {
196 // Previous error has been stored as class. Create a new exception of that type.
197
198 // It's possible the exception doesn't have a <init>(String).
199 std::string temp;
200 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
201
202 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700203 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800204 } else {
205 self->ThrowNewException(descriptor, nullptr);
206 }
207 } else {
208 // Previous error has been stored as an instance. Just rethrow.
Vladimir Markoc13fbd82018-06-04 16:16:28 +0100209 ObjPtr<mirror::Class> throwable_class = GetClassRoot<mirror::Throwable>(class_linker);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700210 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800211 CHECK(throwable_class->IsAssignableFrom(error_class));
212 self->SetException(obj->AsThrowable());
213 }
214 self->AssertPendingException();
215}
216
Andreas Gampe5b20b352018-10-11 19:03:20 -0700217// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
218// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
219// before.
220template <bool kNeedsVerified = false>
221static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
222 REQUIRES_SHARED(Locks::mutator_lock_) {
223 if (kNeedsVerified) {
224 // To not fail access-flags access checks, push a minimal state.
225 mirror::Class::SetStatus(klass, ClassStatus::kVerified, Thread::Current());
226 }
227 if (!klass->WasVerificationAttempted()) {
228 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
229 klass->SetVerificationAttempted();
230 }
231}
232
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800233void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c,
234 bool wrap_in_no_class_def,
235 bool log) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700236 // The class failed to initialize on a previous attempt, so we want to throw
237 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
238 // failed in verification, in which case v2 5.4.1 says we need to re-throw
239 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800240 Runtime* const runtime = Runtime::Current();
241 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700242 std::string extra;
Alex Lightd6251582016-10-31 11:12:30 -0700243 if (GetVerifyError(c) != nullptr) {
244 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
Andreas Gampe369c8512016-01-28 15:31:39 -0800245 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700246 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800247 } else {
248 extra = verify_error->AsThrowable()->Dump();
249 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700250 }
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800251 if (log) {
252 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
253 << ": " << extra;
254 }
Ian Rogers87e552d2012-08-31 15:54:48 -0700255 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700256
David Sehr709b0702016-10-13 09:12:37 -0700257 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800258 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800259 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700260 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700261 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000262 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700263 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700264 if (GetVerifyError(c) != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800265 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800266 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800267 }
Alex Lightd6251582016-10-31 11:12:30 -0700268 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
269 // might have meant to go down the earlier if statement with the original error but it got
270 // swallowed by the OOM so we end up here.
271 if (GetVerifyError(c) == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800272 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
273 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
274 // exception will be a cause.
275 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700276 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700277 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700278 }
279}
280
Brian Carlstromb23eab12014-10-08 17:55:21 -0700281static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700282 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700283 if (VLOG_IS_ON(class_linker)) {
284 std::string temp;
285 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000286 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700287 }
288}
289
290static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700291 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700292 Thread* self = Thread::Current();
293 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700294
295 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700296 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700297
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800298 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
299 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
300 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800301 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800302 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
303 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
304 // could have caused the error.
305 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
306 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
307 << " failed initialization: "
308 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800309 }
310
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700311 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700312 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
313 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700314
Elliott Hughesa4f94742012-05-29 16:28:38 -0700315 // We only wrap non-Error exceptions; an Error can just be used as-is.
316 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000317 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700318 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700319 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700320}
321
Fred Shih381e4ca2014-08-25 17:24:27 -0700322// Gap between two fields in object layout.
323struct FieldGap {
324 uint32_t start_offset; // The offset from the start of the object.
325 uint32_t size; // The gap size of 1, 2, or 4 bytes.
326};
327struct FieldGapsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800328 FieldGapsComparator() {
Fred Shih381e4ca2014-08-25 17:24:27 -0700329 }
330 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
331 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800332 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700333 // Note that the priority queue returns the largest element, so operator()
334 // should return true if lhs is less than rhs.
335 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700336 }
337};
Andreas Gampec55bb392018-09-21 00:02:02 +0000338using FieldGaps = std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator>;
Fred Shih381e4ca2014-08-25 17:24:27 -0700339
340// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800341static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700342 DCHECK(gaps != nullptr);
343
344 uint32_t current_offset = gap_start;
345 while (current_offset != gap_end) {
346 size_t remaining = gap_end - current_offset;
347 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
348 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
349 current_offset += sizeof(uint32_t);
350 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
351 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
352 current_offset += sizeof(uint16_t);
353 } else {
354 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
355 current_offset += sizeof(uint8_t);
356 }
357 DCHECK_LE(current_offset, gap_end) << "Overran gap";
358 }
359}
360// Shuffle fields forward, making use of gaps whenever possible.
361template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000362static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700363 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700364 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700365 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700366 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700367 DCHECK(current_field_idx != nullptr);
368 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700369 DCHECK(gaps != nullptr);
370 DCHECK(field_offset != nullptr);
371
372 DCHECK(IsPowerOfTwo(n));
373 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700374 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700375 Primitive::Type type = field->GetTypeAsPrimitiveType();
376 if (Primitive::ComponentSize(type) < n) {
377 break;
378 }
379 if (!IsAligned<n>(field_offset->Uint32Value())) {
380 MemberOffset old_offset = *field_offset;
381 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
382 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
383 }
David Sehr709b0702016-10-13 09:12:37 -0700384 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700385 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700386 if (!gaps->empty() && gaps->top().size >= n) {
387 FieldGap gap = gaps->top();
388 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100389 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700390 field->SetOffset(MemberOffset(gap.start_offset));
391 if (gap.size > n) {
392 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
393 }
394 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100395 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700396 field->SetOffset(*field_offset);
397 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
398 }
399 ++(*current_field_idx);
400 }
401}
402
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800403ClassLinker::ClassLinker(InternTable* intern_table)
Andreas Gampe2af99022017-04-25 08:32:59 -0700404 : boot_class_table_(new ClassTable()),
405 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800406 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800407 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700408 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000409 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700410 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800411 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800412 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100413 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800414 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700415 image_pointer_size_(kRuntimePointerSize),
Andreas Gampe7dface32017-07-25 21:32:59 -0700416 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
417 // For CHA disabled during Aot, see b/34193647.
418
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700419 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700420 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
421 "Array cache size wrong.");
422 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700423}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700424
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800425void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700426 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800427 if (c2 == nullptr) {
428 LOG(FATAL) << "Could not find class " << descriptor;
429 UNREACHABLE();
430 }
431 if (c1.Get() != c2) {
432 std::ostringstream os1, os2;
433 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
434 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
435 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
436 << ". This is most likely the result of a broken build. Make sure that "
437 << "libcore and art projects match.\n\n"
438 << os1.str() << "\n\n" << os2.str();
439 UNREACHABLE();
440 }
441}
442
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800443bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
444 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800445 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700446
Mathieu Chartiere401d142015-04-22 13:56:20 -0700447 Thread* const self = Thread::Current();
448 Runtime* const runtime = Runtime::Current();
449 gc::Heap* const heap = runtime->GetHeap();
450
Jeff Haodcdc85b2015-12-04 14:06:18 -0800451 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700452 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700453
Mathieu Chartiere401d142015-04-22 13:56:20 -0700454 // Use the pointer size from the runtime since we are probably creating the image.
455 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
456
Elliott Hughes30646832011-10-13 16:59:46 -0700457 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700458 // 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 -0800459 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700460 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700461 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700462 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
463 // the incorrect result when comparing to-space vs from-space.
Vladimir Markobcf17522018-06-01 13:14:32 +0100464 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(MakeObjPtr(
465 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor())))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800466 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100467 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700468 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700469 if (kUseBakerReadBarrier) {
470 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800471 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700472 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700473 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800474 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700475 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700476
Elliott Hughes418d20f2011-09-22 14:00:39 -0700477 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700478 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700479 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700480 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700481 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700482
Ian Rogers23435d02012-09-24 11:23:12 -0700483 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700484 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700485 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800486 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700487 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700488 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000489 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700490
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700491 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800492 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
493 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
494 runtime->SetSentinel(heap->AllocNonMovableObject<true>(self,
495 java_lang_Object.Get(),
496 java_lang_Object->GetObjectSize(),
497 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700498
Igor Murashkin86083f72017-10-27 10:59:04 -0700499 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000500 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700501 // It might seem the lock here is unnecessary, however all the SubtypeCheck
502 // functions are annotated to require locks all the way down.
503 //
504 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
505 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000506 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
507 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700508 }
509
Ian Rogers23435d02012-09-24 11:23:12 -0700510 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700511 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700512 AllocClass(self, java_lang_Class.Get(),
513 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700514 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700515
Roland Levillain0e840272018-08-23 19:55:30 +0100516 // Setup java.lang.String.
517 //
518 // We make this class non-movable for the unlikely case where it were to be
519 // moved by a sticky-bit (minor) collection when using the Generational
520 // Concurrent Copying (CC) collector, potentially creating a stale reference
521 // in the `klass_` field of one of its instances allocated in the Large-Object
522 // Space (LOS) -- see the comment about the dirty card scanning logic in
523 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700524 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700525 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100526 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700527 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000528 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400529
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700530 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700531 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700532 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700533 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000534 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700535
Ian Rogers23435d02012-09-24 11:23:12 -0700536 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700537 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100538 mirror::ObjectArray<mirror::Class>::Alloc(self,
539 object_array_class.Get(),
540 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700541 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100542 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
543 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
544 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
545 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100546 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
547 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700548
Mathieu Chartier6beced42016-11-15 15:51:31 -0800549 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
550 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
551
Vladimir Marko02610552018-06-04 14:38:00 +0100552 // Create array interface entries to populate once we can load system classes.
553 object_array_class->SetIfTable(AllocIfTable(self, 2));
554 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
555
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700556 // Setup the primitive type classes.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100557 SetClassRoot(ClassRoot::kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
558 SetClassRoot(ClassRoot::kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
Vladimir Markoacb906d2018-05-30 10:23:49 +0100559 SetClassRoot(ClassRoot::kPrimitiveChar, CreatePrimitiveClass(self, Primitive::kPrimChar));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100560 SetClassRoot(ClassRoot::kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
561 SetClassRoot(ClassRoot::kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
562 SetClassRoot(ClassRoot::kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
563 SetClassRoot(ClassRoot::kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
564 SetClassRoot(ClassRoot::kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
565 SetClassRoot(ClassRoot::kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700566
Vladimir Markoacb906d2018-05-30 10:23:49 +0100567 // Create int array type for native pointer arrays (for example vtables) on 32-bit archs.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700568 Handle<mirror::Class> int_array_class(hs.NewHandle(
Roland Levillain0e840272018-08-23 19:55:30 +0100569 AllocPrimitiveArrayClass(self, java_lang_Class.Get())));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100570 int_array_class->SetComponentType(GetClassRoot(ClassRoot::kPrimitiveInt, this));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100571 SetClassRoot(ClassRoot::kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700572
Vladimir Markoacb906d2018-05-30 10:23:49 +0100573 // Create long array type for native pointer arrays (for example vtables) on 64-bit archs.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700574 Handle<mirror::Class> long_array_class(hs.NewHandle(
Roland Levillain0e840272018-08-23 19:55:30 +0100575 AllocPrimitiveArrayClass(self, java_lang_Class.Get())));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100576 long_array_class->SetComponentType(GetClassRoot(ClassRoot::kPrimitiveLong, this));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100577 SetClassRoot(ClassRoot::kLongArrayClass, long_array_class.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700578
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700579 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700580
Ian Rogers52813c92012-10-11 11:50:38 -0700581 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700582 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700583 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100584 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100585 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700586 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000587 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700588
Alex Lightd6251582016-10-31 11:12:30 -0700589
590 // Setup dalvik.system.ClassExt
591 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
592 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100593 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000594 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700595
Mathieu Chartier66f19252012-09-18 08:57:04 -0700596 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700597 Handle<mirror::Class> object_array_string(hs.NewHandle(
598 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700599 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700600 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100601 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700602
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000603 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700604 // Create runtime resolution and imt conflict methods.
605 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000606 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
607 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700608
Ian Rogers23435d02012-09-24 11:23:12 -0700609 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
610 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
611 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800612 if (boot_class_path.empty()) {
613 *error_msg = "Boot classpath is empty.";
614 return false;
615 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800616 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800617 if (dex_file.get() == nullptr) {
618 *error_msg = "Null dex file.";
619 return false;
620 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700621 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800622 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700623 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700624
625 // now we can use FindSystemClass
626
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700627 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
628 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700629 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800630 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700631 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700632 quick_resolution_trampoline_ = GetQuickResolutionStub();
633 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
634 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700635 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700636
Alex Lightd6251582016-10-31 11:12:30 -0700637 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000638 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800639 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700640 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000641 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800642 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000643 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800644 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700645 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000646 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700647 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
648 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700649
Ian Rogers23435d02012-09-24 11:23:12 -0700650 // Setup the primitive array type classes - can't be done until Object has a vtable.
Roland Levillain0e840272018-08-23 19:55:30 +0100651 AllocAndSetPrimitiveArrayClassRoot(self,
652 java_lang_Class.Get(),
653 ClassRoot::kBooleanArrayClass,
654 ClassRoot::kPrimitiveBoolean,
655 "[Z");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700656
Roland Levillain0e840272018-08-23 19:55:30 +0100657 AllocAndSetPrimitiveArrayClassRoot(
658 self, java_lang_Class.Get(), ClassRoot::kByteArrayClass, ClassRoot::kPrimitiveByte, "[B");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700659
Roland Levillain0e840272018-08-23 19:55:30 +0100660 AllocAndSetPrimitiveArrayClassRoot(
661 self, java_lang_Class.Get(), ClassRoot::kCharArrayClass, ClassRoot::kPrimitiveChar, "[C");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700662
Roland Levillain0e840272018-08-23 19:55:30 +0100663 AllocAndSetPrimitiveArrayClassRoot(
664 self, java_lang_Class.Get(), ClassRoot::kShortArrayClass, ClassRoot::kPrimitiveShort, "[S");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700665
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800666 CheckSystemClass(self, int_array_class, "[I");
667 CheckSystemClass(self, long_array_class, "[J");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700668
Roland Levillain0e840272018-08-23 19:55:30 +0100669 AllocAndSetPrimitiveArrayClassRoot(
670 self, java_lang_Class.Get(), ClassRoot::kFloatArrayClass, ClassRoot::kPrimitiveFloat, "[F");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700671
Roland Levillain0e840272018-08-23 19:55:30 +0100672 AllocAndSetPrimitiveArrayClassRoot(
673 self, java_lang_Class.Get(), ClassRoot::kDoubleArrayClass, ClassRoot::kPrimitiveDouble, "[D");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700674
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800675 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
676 // in class_table_.
677 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700678
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800679 CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;");
680 CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700681
Ian Rogers23435d02012-09-24 11:23:12 -0700682 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700683 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800684 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700685 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800686 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700687 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
688 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100689 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
690 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700691
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700692 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
693 // suspension.
694 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000695 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700696 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000697 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700698 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000699 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700700 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000701 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700702
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700703 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100704 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700705
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800706 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700707
Ian Rogers23435d02012-09-24 11:23:12 -0700708 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100709 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
710 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700711
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700712 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100713 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700714 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100715 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700716
717 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700718 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
719 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100720 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700721
722 // Create java.lang.reflect.Constructor.class root and array root.
723 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
724 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100725 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700726 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
727 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100728 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700729
730 // Create java.lang.reflect.Method.class root and array root.
731 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
732 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100733 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700734 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
735 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100736 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700737
Orion Hodson005ac512017-10-24 15:43:43 +0100738 // Create java.lang.invoke.CallSite.class root
739 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
740 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100741 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100742
Narayan Kamathafa48272016-08-03 12:46:58 +0100743 // Create java.lang.invoke.MethodType.class root
744 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
745 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100746 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100747
748 // Create java.lang.invoke.MethodHandleImpl.class root
749 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
750 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100751 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100752 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +0100753
Orion Hodsonc069a302017-01-18 09:23:12 +0000754 // Create java.lang.invoke.MethodHandles.Lookup.class root
755 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
756 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100757 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000758
Orion Hodson005ac512017-10-24 15:43:43 +0100759 // Create java.lang.invoke.VarHandle.class root
760 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000761 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100762 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100763
764 // Create java.lang.invoke.FieldVarHandle.class root
765 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
766 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100767 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100768
769 // Create java.lang.invoke.ArrayElementVarHandle.class root
770 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
771 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100772 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100773
774 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
775 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
776 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100777 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100778
779 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
780 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
781 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100782 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000783
Narayan Kamath000e1882016-10-24 17:14:25 +0100784 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
785 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100786 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100787
Brian Carlstrom1f870082011-08-23 16:02:11 -0700788 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700789 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000790 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800791 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700792 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700793 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
794 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700795 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700796 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700797 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700798 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700799 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700800 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700801 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700802 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700803 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700804 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700805 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700806 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700807
Ian Rogers23435d02012-09-24 11:23:12 -0700808 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700809 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700810 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700811 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100812 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700813
jeffhao8cd6dda2012-02-22 10:15:34 -0800814 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700815 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100816 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100817 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -0700818 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100819 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
820 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
821 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -0700822 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000823 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
824 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700825
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700826 // Create conflict tables that depend on the class linker.
827 runtime->FixupConflictTables();
828
Ian Rogers98379392014-02-24 16:53:16 -0800829 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700830
Brian Carlstroma004aa92012-02-08 18:05:09 -0800831 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800832
833 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700834}
835
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700836static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
837 REQUIRES_SHARED(Locks::mutator_lock_) {
838 // Find String.<init> -> StringFactory bindings.
839 ObjPtr<mirror::Class> string_factory_class =
840 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
841 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100842 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700843 WellKnownClasses::InitStringInit(string_class, string_factory_class);
844 // Update the primordial thread.
845 self->InitStringEntryPoints();
846}
847
Ian Rogers98379392014-02-24 16:53:16 -0800848void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800849 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700850
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700851 CreateStringInitBindings(self, this);
852
Brian Carlstrom16192862011-09-12 17:50:06 -0700853 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700854 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700855 // as the types of the field can't be resolved prior to the runtime being
856 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -0700857 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100858 Handle<mirror::Class> java_lang_ref_Reference =
859 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700860 Handle<mirror::Class> java_lang_ref_FinalizerReference =
861 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800862
Mathieu Chartierc7853442015-03-27 14:35:38 -0700863 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700864 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
865 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700866
Mathieu Chartierc7853442015-03-27 14:35:38 -0700867 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700868 CHECK_STREQ(queue->GetName(), "queue");
869 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700870
Mathieu Chartierc7853442015-03-27 14:35:38 -0700871 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700872 CHECK_STREQ(queueNext->GetName(), "queueNext");
873 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700874
Mathieu Chartierc7853442015-03-27 14:35:38 -0700875 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700876 CHECK_STREQ(referent->GetName(), "referent");
877 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700878
Mathieu Chartierc7853442015-03-27 14:35:38 -0700879 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700880 CHECK_STREQ(zombie->GetName(), "zombie");
881 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700882
Brian Carlstroma663ea52011-08-19 23:33:41 -0700883 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100884 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700885 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700886 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700887 CHECK(klass != nullptr);
888 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700889 // note SetClassRoot does additional validation.
890 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700891 }
892
Vladimir Marko02610552018-06-04 14:38:00 +0100893 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700894
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700895 // disable the slow paths in FindClass and CreatePrimitiveClass now
896 // that Object, Class, and Object[] are setup
897 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700898
Andreas Gampe7b2450e2018-06-19 10:45:54 -0700899 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
900 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
901 // ensure that the class will be initialized.
902 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
903 verifier::MethodVerifier::Init(); // Need to prepare the verifier.
904
905 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
906 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
907 // Strange, but don't crash.
908 LOG(WARNING) << "Could not prepare StackOverflowError.";
909 self->ClearException();
910 }
911 }
912
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800913 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700914}
915
Vladimir Markodcfcce42018-06-27 10:00:28 +0000916void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100917 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
918 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700919 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700920 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100921 Handle<mirror::Class> h_class(hs.NewHandle(c));
Ian Rogers7b078e82014-09-10 14:44:24 -0700922 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700923 self->AssertNoPendingException();
Vladimir Markodcfcce42018-06-27 10:00:28 +0000924 } else {
925 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700926 }
927 }
928}
929
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200930// Set image methods' entry point to interpreter.
931class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor {
932 public:
Andreas Gampe542451c2016-07-26 09:02:02 -0700933 explicit SetInterpreterEntrypointArtMethodVisitor(PointerSize image_pointer_size)
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200934 : image_pointer_size_(image_pointer_size) {}
935
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100936 void Visit(ArtMethod* method) override REQUIRES_SHARED(Locks::mutator_lock_) {
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200937 if (kIsDebugBuild && !method->IsRuntimeMethod()) {
938 CHECK(method->GetDeclaringClass() != nullptr);
939 }
940 if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
941 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
942 image_pointer_size_);
943 }
944 }
945
946 private:
Andreas Gampe542451c2016-07-26 09:02:02 -0700947 const PointerSize image_pointer_size_;
Sebastien Hertz46e857a2015-08-06 12:52:43 +0200948
949 DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor);
950};
951
Jeff Haodcdc85b2015-12-04 14:06:18 -0800952struct TrampolineCheckData {
953 const void* quick_resolution_trampoline;
954 const void* quick_imt_conflict_trampoline;
955 const void* quick_generic_jni_trampoline;
956 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -0700957 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800958 ArtMethod* m;
959 bool error;
960};
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800961
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800962bool ClassLinker::InitFromBootImage(std::string* error_msg) {
963 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700964 CHECK(!init_done_);
965
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700966 Runtime* const runtime = Runtime::Current();
967 Thread* const self = Thread::Current();
968 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800969 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
970 CHECK(!spaces.empty());
Andreas Gampe542451c2016-07-26 09:02:02 -0700971 uint32_t pointer_size_unchecked = spaces[0]->GetImageHeader().GetPointerSizeUnchecked();
972 if (!ValidPointerSize(pointer_size_unchecked)) {
973 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800974 return false;
975 }
Andreas Gampe542451c2016-07-26 09:02:02 -0700976 image_pointer_size_ = spaces[0]->GetImageHeader().GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800977 if (!runtime->IsAotCompiler()) {
978 // Only the Aot compiler supports having an image with a different pointer size than the
979 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
980 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -0700981 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800982 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -0700983 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800984 sizeof(void*));
985 return false;
986 }
987 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800988 std::vector<const OatFile*> oat_files =
989 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
990 DCHECK(!oat_files.empty());
991 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800992 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
993 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
994 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
995 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
996 if (kIsDebugBuild) {
997 // Check that the other images use the same trampoline.
998 for (size_t i = 1; i < oat_files.size(); ++i) {
999 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
1000 const void* ith_quick_resolution_trampoline =
1001 ith_oat_header.GetQuickResolutionTrampoline();
1002 const void* ith_quick_imt_conflict_trampoline =
1003 ith_oat_header.GetQuickImtConflictTrampoline();
1004 const void* ith_quick_generic_jni_trampoline =
1005 ith_oat_header.GetQuickGenericJniTrampoline();
1006 const void* ith_quick_to_interpreter_bridge_trampoline =
1007 ith_oat_header.GetQuickToInterpreterBridge();
1008 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
1009 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1010 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
1011 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
1012 // Make sure that all methods in this image do not contain those trampolines as
1013 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1014 TrampolineCheckData data;
1015 data.error = false;
1016 data.pointer_size = GetImagePointerSize();
1017 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1018 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1019 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1020 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
1021 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001022 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1023 if (obj->IsClass()) {
1024 ObjPtr<mirror::Class> klass = obj->AsClass();
1025 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1026 const void* entrypoint =
1027 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1028 if (entrypoint == data.quick_resolution_trampoline ||
1029 entrypoint == data.quick_imt_conflict_trampoline ||
1030 entrypoint == data.quick_generic_jni_trampoline ||
1031 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1032 data.m = &m;
1033 data.error = true;
1034 return;
1035 }
1036 }
1037 }
1038 };
1039 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001040 if (data.error) {
1041 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001042 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001043 *error_msg = "Found an ArtMethod with a bad entrypoint";
1044 return false;
1045 }
1046 }
1047 }
1048 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001049
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001050 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markobcf17522018-06-01 13:14:32 +01001051 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(MakeObjPtr(
1052 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots))));
Vladimir Markof75613c2018-06-05 12:51:04 +01001053 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001054
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001055 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001056 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001057 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
1058 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001059 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
1060 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001061
Vladimir Marko4433c432018-12-04 14:57:47 +00001062 const std::vector<std::string>& boot_class_path_locations = runtime->GetBootClassPathLocations();
1063 CHECK_LE(spaces.size(), boot_class_path_locations.size());
Vladimir Markod1908512018-11-22 14:57:28 +00001064 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001065 // Boot class loader, use a null handle.
1066 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001067 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001068 ScopedNullHandle<mirror::ClassLoader>(),
Vladimir Markod1908512018-11-22 14:57:28 +00001069 /*dex_elements=*/ nullptr,
Vladimir Marko4433c432018-12-04 14:57:47 +00001070 /*dex_location=*/ boot_class_path_locations[i].c_str(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001071 /*out*/&dex_files,
1072 error_msg)) {
1073 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001074 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001075 // Append opened dex files at the end.
1076 boot_dex_files_.insert(boot_dex_files_.end(),
1077 std::make_move_iterator(dex_files.begin()),
1078 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001079 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001080 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1081 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1082 }
Ian Rogers98379392014-02-24 16:53:16 -08001083 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001084
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001085 VLOG(startup) << __FUNCTION__ << " exiting";
1086 return true;
1087}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001088
Vladimir Marko4433c432018-12-04 14:57:47 +00001089void ClassLinker::AddExtraBootDexFiles(
1090 Thread* self,
1091 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1092 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
1093 AppendToBootClassPath(self, *dex_file);
1094 boot_dex_files_.push_back(std::move(dex_file));
1095 }
1096}
1097
Jeff Hao5872d7c2016-04-27 11:07:41 -07001098bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001099 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001100 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001101 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1102 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001103}
1104
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001105static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1106 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001107 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001108 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001109 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001110 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001111 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001112 DCHECK(dex_file_field != nullptr);
1113 DCHECK(dex_file_name_field != nullptr);
1114 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001115 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001116 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001117 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001118 // Null dex file means it was probably a jar with no dex files, return a null string.
1119 *out_name = nullptr;
1120 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001121 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001122 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001123 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001124 *out_name = name_object->AsString();
1125 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001126 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001127 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001128}
1129
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001130static bool GetDexFileNames(ScopedObjectAccessUnchecked& soa,
1131 ObjPtr<mirror::ClassLoader> class_loader,
1132 /*out*/std::list<ObjPtr<mirror::String>>* dex_files,
1133 /*out*/std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001134 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001135 StackHandleScope<1> hs(soa.Self());
1136 Handle<mirror::ClassLoader> handle(hs.NewHandle(class_loader));
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001137 // Get element names. Sets error to true on failure.
1138 auto add_element_names = [&](ObjPtr<mirror::Object> element, bool* error)
1139 REQUIRES_SHARED(Locks::mutator_lock_) {
1140 if (element == nullptr) {
1141 *error_msg = "Null dex element";
1142 *error = true; // Null element is a critical error.
1143 return false; // Had an error, stop the visit.
1144 }
1145 ObjPtr<mirror::String> name;
1146 if (!GetDexPathListElementName(element, &name)) {
1147 *error_msg = "Invalid dex path list element";
1148 *error = true; // Invalid element, make it a critical error.
1149 return false; // Stop the visit.
1150 }
1151 if (name != nullptr) {
1152 dex_files->push_front(name);
1153 }
1154 return true; // Continue with the next Element.
1155 };
1156 bool error = VisitClassLoaderDexElements(soa,
1157 handle,
1158 add_element_names,
1159 /*defaultReturn=*/ false);
1160 return !error;
1161}
1162
1163static bool CompareClassLoaderTypes(ScopedObjectAccessUnchecked& soa,
1164 ObjPtr<mirror::ClassLoader> image_class_loader,
1165 ObjPtr<mirror::ClassLoader> class_loader,
1166 std::string* error_msg)
1167 REQUIRES_SHARED(Locks::mutator_lock_) {
1168 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1169 if (!ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1170 *error_msg = "Hierarchies don't match";
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001171 return false;
1172 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001173 } else if (ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1174 *error_msg = "Hierarchies don't match";
1175 return false;
1176 } else if (class_loader->GetClass() != image_class_loader->GetClass()) {
1177 *error_msg = StringPrintf("Class loader types don't match %s and %s",
1178 image_class_loader->PrettyTypeOf().c_str(),
1179 class_loader->PrettyTypeOf().c_str());
1180 return false;
1181 } else if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1182 class_loader->GetClass()) {
1183 *error_msg = StringPrintf("Unknown class loader type %s",
1184 class_loader->PrettyTypeOf().c_str());
1185 // Unsupported class loader.
1186 return false;
1187 }
1188 return true;
1189}
1190
1191static bool CompareDexFiles(const std::list<ObjPtr<mirror::String>>& image_dex_files,
1192 const std::list<ObjPtr<mirror::String>>& loader_dex_files,
1193 std::string* error_msg)
1194 REQUIRES_SHARED(Locks::mutator_lock_) {
1195 bool equal = (image_dex_files.size() == loader_dex_files.size()) &&
1196 std::equal(image_dex_files.begin(),
1197 image_dex_files.end(),
1198 loader_dex_files.begin(),
1199 [](ObjPtr<mirror::String> lhs, ObjPtr<mirror::String> rhs)
1200 REQUIRES_SHARED(Locks::mutator_lock_) {
1201 return lhs->Equals(rhs);
1202 });
1203 if (!equal) {
1204 VLOG(image) << "Image dex files " << image_dex_files.size();
1205 for (ObjPtr<mirror::String> name : image_dex_files) {
1206 VLOG(image) << name->ToModifiedUtf8();
1207 }
1208 VLOG(image) << "Loader dex files " << loader_dex_files.size();
1209 for (ObjPtr<mirror::String> name : loader_dex_files) {
1210 VLOG(image) << name->ToModifiedUtf8();
1211 }
1212 *error_msg = "Mismatch in dex files";
1213 }
1214 return equal;
1215}
1216
1217static bool CompareClassLoaders(ScopedObjectAccessUnchecked& soa,
1218 ObjPtr<mirror::ClassLoader> image_class_loader,
1219 ObjPtr<mirror::ClassLoader> class_loader,
1220 bool check_dex_file_names,
1221 std::string* error_msg)
1222 REQUIRES_SHARED(Locks::mutator_lock_) {
1223 if (!CompareClassLoaderTypes(soa, image_class_loader, class_loader, error_msg)) {
1224 return false;
1225 }
1226
1227 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1228 // No need to check further.
1229 return true;
1230 }
1231
1232 if (check_dex_file_names) {
1233 std::list<ObjPtr<mirror::String>> image_dex_files;
1234 if (!GetDexFileNames(soa, image_class_loader, &image_dex_files, error_msg)) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001235 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001236 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001237
1238 std::list<ObjPtr<mirror::String>> loader_dex_files;
1239 if (!GetDexFileNames(soa, class_loader, &loader_dex_files, error_msg)) {
1240 return false;
1241 }
1242
1243 if (!CompareDexFiles(image_dex_files, loader_dex_files, error_msg)) {
1244 return false;
1245 }
1246 }
1247
1248 ArtField* field =
1249 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
1250 ObjPtr<mirror::Object> shared_libraries_image_loader = field->GetObject(image_class_loader.Ptr());
1251 ObjPtr<mirror::Object> shared_libraries_loader = field->GetObject(class_loader.Ptr());
1252 if (shared_libraries_image_loader == nullptr) {
1253 if (shared_libraries_loader != nullptr) {
1254 *error_msg = "Mismatch in shared libraries";
1255 return false;
1256 }
1257 } else if (shared_libraries_loader == nullptr) {
1258 *error_msg = "Mismatch in shared libraries";
1259 return false;
1260 } else {
1261 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array1 =
1262 shared_libraries_image_loader->AsObjectArray<mirror::ClassLoader>();
1263 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array2 =
1264 shared_libraries_loader->AsObjectArray<mirror::ClassLoader>();
1265 if (array1->GetLength() != array2->GetLength()) {
1266 *error_msg = "Mismatch in number of shared libraries";
1267 return false;
1268 }
1269
1270 for (int32_t i = 0; i < array1->GetLength(); ++i) {
1271 // Do a full comparison of the class loaders, including comparing their dex files.
1272 if (!CompareClassLoaders(soa,
1273 array1->Get(i),
1274 array2->Get(i),
1275 /*check_dex_file_names=*/ true,
1276 error_msg)) {
1277 return false;
1278 }
1279 }
1280 }
1281
1282 // Do a full comparison of the class loaders, including comparing their dex files.
1283 if (!CompareClassLoaders(soa,
1284 image_class_loader->GetParent(),
1285 class_loader->GetParent(),
1286 /*check_dex_file_names=*/ true,
1287 error_msg)) {
1288 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001289 }
1290 return true;
1291}
1292
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001293class CHAOnDeleteUpdateClassVisitor {
1294 public:
1295 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1296 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1297 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1298 self_(Thread::Current()) {}
1299
1300 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1301 // This class is going to be unloaded. Tell CHA about it.
1302 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1303 return true;
1304 }
1305 private:
1306 const LinearAlloc* allocator_;
1307 const ClassHierarchyAnalysis* cha_;
1308 const PointerSize pointer_size_;
1309 const Thread* self_;
1310};
1311
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001312class VerifyDeclaringClassVisitor : public ArtMethodVisitor {
1313 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001314 VerifyDeclaringClassVisitor() REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001315 : live_bitmap_(Runtime::Current()->GetHeap()->GetLiveBitmap()) {}
1316
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001317 void Visit(ArtMethod* method) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001318 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001319 ObjPtr<mirror::Class> klass = method->GetDeclaringClassUnchecked();
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001320 if (klass != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001321 CHECK(live_bitmap_->Test(klass.Ptr())) << "Image method has unmarked declaring class";
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001322 }
1323 }
1324
1325 private:
1326 gc::accounting::HeapBitmap* const live_bitmap_;
1327};
1328
Chris Wailes0c61be42018-09-26 17:27:34 -07001329/*
1330 * A class used to ensure that all strings in an AppImage have been properly
Chris Wailesfbeef462018-10-19 14:16:35 -07001331 * interned, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001332 */
1333class VerifyStringInterningVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001334 public:
Chris Wailes0c61be42018-09-26 17:27:34 -07001335 explicit VerifyStringInterningVisitor(const gc::space::ImageSpace& space) :
Chris Wailes0c61be42018-09-26 17:27:34 -07001336 space_(space),
1337 intern_table_(*Runtime::Current()->GetInternTable()) {}
1338
Chris Wailes0c61be42018-09-26 17:27:34 -07001339 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001340 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001341 if (referred_obj != nullptr &&
1342 space_.HasAddress(referred_obj.Ptr()) &&
1343 referred_obj->IsString()) {
1344 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Chris Wailesfbeef462018-10-19 14:16:35 -07001345
1346 if (kIsDebugBuild) {
1347 // Saved to temporary variables to aid in debugging.
1348 ObjPtr<mirror::String> strong_lookup_result =
1349 intern_table_.LookupStrong(Thread::Current(), referred_str);
1350 ObjPtr<mirror::String> weak_lookup_result =
1351 intern_table_.LookupWeak(Thread::Current(), referred_str);
1352
1353 DCHECK((strong_lookup_result == referred_str) || (weak_lookup_result == referred_str));
1354 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001355 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001356 }
1357
Chris Wailes0c61be42018-09-26 17:27:34 -07001358 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001359 mirror::CompressedReference<mirror::Object>* root) const
1360 REQUIRES_SHARED(Locks::mutator_lock_) {
1361 if (!root->IsNull()) {
1362 VisitRoot(root);
1363 }
1364 }
1365
Chris Wailes0c61be42018-09-26 17:27:34 -07001366 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001367 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001368 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001369 }
1370
1371 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001372 void operator()(ObjPtr<mirror::Object> obj,
1373 MemberOffset offset,
1374 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001375 REQUIRES_SHARED(Locks::mutator_lock_) {
1376 // There could be overlap between ranges, we must avoid visiting the same reference twice.
1377 // Avoid the class field since we already fixed it up in FixupClassVisitor.
1378 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
1379 // Updating images, don't do a read barrier.
Chris Wailes0c61be42018-09-26 17:27:34 -07001380 ObjPtr<mirror::Object> referred_obj =
1381 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1382
1383 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001384 }
1385 }
1386
1387 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1388 ObjPtr<mirror::Reference> ref) const
1389 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001390 operator()(ref, mirror::Reference::ReferentOffset(), false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001391 }
1392
Chris Wailes0c61be42018-09-26 17:27:34 -07001393 const gc::space::ImageSpace& space_;
1394 InternTable& intern_table_;
Chang Xingba17dbd2017-06-28 21:27:56 +00001395};
1396
Chris Wailes0c61be42018-09-26 17:27:34 -07001397/*
1398 * This function verifies that string references in the AppImage have been
1399 * properly interned. To be considered properly interned a reference must
1400 * point to the same version of the string that the intern table does.
1401 */
Chris Wailesfbeef462018-10-19 14:16:35 -07001402void VerifyStringInterning(gc::space::ImageSpace& space) REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001403 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1404 const ImageHeader& image_header = space.GetImageHeader();
1405 const uint8_t* target_base = space.GetMemMap()->Begin();
1406 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001407
1408 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1409 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001410
1411 VerifyStringInterningVisitor visitor(space);
1412 bitmap->VisitMarkedRange(objects_begin,
1413 objects_end,
1414 [&space, &visitor](mirror::Object* obj)
1415 REQUIRES_SHARED(Locks::mutator_lock_) {
1416 if (space.HasAddress(obj)) {
1417 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001418 obj->VisitReferences</* kVisitNativeRoots= */ true,
1419 kVerifyNone,
1420 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001421 } else {
1422 // Don't visit native roots for non-dex-cache as they can't contain
1423 // native references to strings. This is verified during compilation
1424 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001425 obj->VisitReferences</* kVisitNativeRoots= */ false,
1426 kVerifyNone,
1427 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001428 }
1429 }
1430 });
Chris Wailes0c61be42018-09-26 17:27:34 -07001431}
1432
Andreas Gampe2af99022017-04-25 08:32:59 -07001433// new_class_set is the set of classes that were read from the class table section in the image.
1434// If there was no class table section, it is null.
1435// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001436class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001437 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001438 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001439 ClassLinker* class_linker,
1440 gc::space::ImageSpace* space,
1441 Handle<mirror::ClassLoader> class_loader,
1442 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001443 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001444 REQUIRES(!Locks::dex_lock_)
1445 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001446
Chris Wailesfbeef462018-10-19 14:16:35 -07001447 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001448 REQUIRES_SHARED(Locks::mutator_lock_);
1449
1450 static void UpdateInternStrings(
1451 gc::space::ImageSpace* space,
1452 const SafeMap<mirror::String*, mirror::String*>& intern_remap)
1453 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001454};
1455
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001456void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001457 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001458 gc::space::ImageSpace* space,
1459 Handle<mirror::ClassLoader> class_loader,
1460 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001461 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001462 REQUIRES(!Locks::dex_lock_)
1463 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001464 ScopedTrace app_image_timing("AppImage:Updating");
1465
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001466 Thread* const self = Thread::Current();
1467 gc::Heap* const heap = Runtime::Current()->GetHeap();
1468 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001469 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001470 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001471 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001472 const size_t num_dex_caches = dex_caches->GetLength();
1473 for (size_t i = 0; i < num_dex_caches; i++) {
Vladimir Marko1bc4b172016-10-24 16:53:39 +00001474 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001475 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001476 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001477 WriterMutexLock mu2(self, *Locks::dex_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001478 CHECK(!class_linker->FindDexCacheDataLocked(*dex_file).IsValid());
1479 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001480 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001481
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001482 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001483 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001484 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001485 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001486 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001487 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001488 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Chris Wailes0c61be42018-09-26 17:27:34 -07001489
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001490 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001491 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Vladimir Marko54159c62018-06-20 14:30:08 +01001492 auto it = new_class_set->find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001493 DCHECK(it != new_class_set->end());
1494 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001495 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Chris Wailes0c61be42018-09-26 17:27:34 -07001496
Vladimir Marko1a1de672016-10-13 12:53:15 +01001497 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Vladimir Marko54159c62018-06-20 14:30:08 +01001498 auto it2 = new_class_set->find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001499 DCHECK(it2 != new_class_set->end());
1500 DCHECK_EQ(it2->Read(), super_class);
1501 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001502
Vladimir Marko1a1de672016-10-13 12:53:15 +01001503 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1504 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001505 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1506 if (!class_linker->IsQuickResolutionStub(code) &&
1507 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001508 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001509 !m.IsNative()) {
1510 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001511 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001512 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001513
Vladimir Marko1a1de672016-10-13 12:53:15 +01001514 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1515 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001516 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1517 if (!class_linker->IsQuickResolutionStub(code) &&
1518 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001519 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001520 !m.IsNative()) {
1521 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001522 }
1523 }
1524 }
1525 }
1526 }
1527 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001528 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001529
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001530 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001531 HandleAppImageStrings(space);
1532
1533 if (kIsDebugBuild) {
1534 VerifyStringInterning(*space);
1535 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001536 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001537
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001538 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001539 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001540 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1541 VerifyDeclaringClassVisitor visitor;
Andreas Gampe542451c2016-07-26 09:02:02 -07001542 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001543 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001544}
1545
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001546void AppImageLoadingHelper::UpdateInternStrings(
1547 gc::space::ImageSpace* space,
1548 const SafeMap<mirror::String*, mirror::String*>& intern_remap) {
1549 const uint8_t* target_base = space->Begin();
Chris Wailesfbeef462018-10-19 14:16:35 -07001550 const ImageSection& sro_section =
1551 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1552 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001553
1554 VLOG(image)
1555 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1556 << num_string_offsets;
1557
Chris Wailesfbeef462018-10-19 14:16:35 -07001558 const auto* sro_base =
1559 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001560
1561 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001562 uint32_t base_offset = sro_base[offset_index].first;
1563
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001564 if (HasDexCacheStringNativeRefTag(base_offset)) {
1565 base_offset = ClearDexCacheNativeRefTags(base_offset);
1566 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001567
1568 ObjPtr<mirror::DexCache> dex_cache =
1569 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1570 uint32_t string_index = sro_base[offset_index].second;
1571
1572 mirror::StringDexCachePair source = dex_cache->GetStrings()[string_index].load();
1573 ObjPtr<mirror::String> referred_string = source.object.Read();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001574 DCHECK(referred_string != nullptr);
1575
Chris Wailesfbeef462018-10-19 14:16:35 -07001576 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001577 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001578 // This doesn't use SetResolvedString to maintain consistency with how
1579 // we load the string. The index from the source string must be
1580 // re-used due to the circular nature of the cache. Because we are not
1581 // using a helper function we need to mark the GC card manually.
1582 WriteBarrier::ForEveryFieldWrite(dex_cache);
1583 dex_cache->GetStrings()[string_index].store(
1584 mirror::StringDexCachePair(it->second, source.index));
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001585 }
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001586 } else if (HasDexCachePreResolvedStringNativeRefTag(base_offset)) {
1587 base_offset = ClearDexCacheNativeRefTags(base_offset);
1588 DCHECK_ALIGNED(base_offset, 2);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001589
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001590 ObjPtr<mirror::DexCache> dex_cache =
1591 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1592 uint32_t string_index = sro_base[offset_index].second;
1593
1594 ObjPtr<mirror::String> referred_string =
1595 dex_cache->GetPreResolvedStrings()[string_index].Read();
1596 DCHECK(referred_string != nullptr);
1597
1598 auto it = intern_remap.find(referred_string.Ptr());
1599 if (it != intern_remap.end()) {
1600 // Because we are not using a helper function we need to mark the GC card manually.
1601 WriteBarrier::ForEveryFieldWrite(dex_cache);
1602 dex_cache->GetPreResolvedStrings()[string_index] = GcRoot<mirror::String>(it->second);
1603 }
Chris Wailesfbeef462018-10-19 14:16:35 -07001604 } else {
1605 uint32_t raw_member_offset = sro_base[offset_index].second;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001606 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001607 DCHECK_ALIGNED(raw_member_offset, 2);
1608
1609 ObjPtr<mirror::Object> obj_ptr =
1610 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1611 MemberOffset member_offset(raw_member_offset);
1612 ObjPtr<mirror::String> referred_string =
1613 obj_ptr->GetFieldObject<mirror::String,
1614 kVerifyNone,
1615 kWithoutReadBarrier,
1616 /* kIsVolatile= */ false>(member_offset);
1617 DCHECK(referred_string != nullptr);
1618
1619 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001620 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001621 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1622 /* kCheckTransaction= */ false,
1623 kVerifyNone,
1624 /* kIsVolatile= */ false>(member_offset, it->second);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001625 }
1626 }
1627 }
1628}
1629
Chris Wailesfbeef462018-10-19 14:16:35 -07001630void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001631 // Iterate over the string reference offsets stored in the image and intern
1632 // the strings they point to.
1633 ScopedTrace timing("AppImage:InternString");
1634
Chris Wailesfbeef462018-10-19 14:16:35 -07001635 InternTable* const intern_table = Runtime::Current()->GetInternTable();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001636
1637 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1638 // for faster lookup.
1639 // TODO: Optimize with a bitmap or bloom filter
1640 SafeMap<mirror::String*, mirror::String*> intern_remap;
1641 intern_table->AddImageStringsToTable(space, [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001642 REQUIRES_SHARED(Locks::mutator_lock_)
1643 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001644 const size_t non_boot_image_strings = intern_table->CountInterns(
1645 /*visit_boot_images=*/false,
1646 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001647 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001648 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1649 // Visit the smaller of the two sets to compute the intersection.
1650 if (interns.size() < non_boot_image_strings) {
1651 for (auto it = interns.begin(); it != interns.end(); ) {
1652 ObjPtr<mirror::String> string = it->Read();
1653 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1654 if (existing == nullptr) {
1655 existing = intern_table->LookupStrongLocked(string);
1656 }
1657 if (existing != nullptr) {
1658 intern_remap.Put(string.Ptr(), existing.Ptr());
1659 it = interns.erase(it);
1660 } else {
1661 ++it;
1662 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001663 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001664 } else {
1665 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1666 REQUIRES_SHARED(Locks::mutator_lock_)
1667 REQUIRES(Locks::intern_table_lock_) {
1668 auto it = interns.find(root);
1669 if (it != interns.end()) {
1670 ObjPtr<mirror::String> existing = root.Read();
1671 intern_remap.Put(it->Read(), existing.Ptr());
1672 it = interns.erase(it);
1673 }
1674 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1675 }
1676 // Sanity check to ensure correctness.
1677 if (kIsDebugBuild) {
1678 for (GcRoot<mirror::String>& root : interns) {
1679 ObjPtr<mirror::String> string = root.Read();
1680 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1681 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001682 }
1683 }
1684 });
1685
Chris Wailesfbeef462018-10-19 14:16:35 -07001686 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001687
1688 // For debug builds, always run the code below to get coverage.
1689 if (kIsDebugBuild || !intern_remap.empty()) {
1690 // Slow path case is when there are conflicting intern strings to fix up.
1691 UpdateInternStrings(space, intern_remap);
1692 }
1693}
1694
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001695static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1696 const char* location,
1697 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001698 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001699 DCHECK(error_msg != nullptr);
1700 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001701 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001702 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001703 return std::unique_ptr<const DexFile>();
1704 }
1705 std::string inner_error_msg;
1706 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1707 if (dex_file == nullptr) {
1708 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1709 location,
1710 oat_file->GetLocation().c_str(),
1711 inner_error_msg.c_str());
1712 return std::unique_ptr<const DexFile>();
1713 }
1714
1715 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1716 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1717 location,
1718 dex_file->GetLocationChecksum(),
1719 oat_dex_file->GetDexFileLocationChecksum());
1720 return std::unique_ptr<const DexFile>();
1721 }
1722 return dex_file;
1723}
1724
1725bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1726 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1727 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001728 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001729 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001730 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001731 DCHECK(dex_caches_object != nullptr);
1732 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1733 dex_caches_object->AsObjectArray<mirror::DexCache>();
1734 const OatFile* oat_file = space->GetOatFile();
1735 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001736 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001737 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1738 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1739 dex_file_location.c_str(),
1740 error_msg);
1741 if (dex_file == nullptr) {
1742 return false;
1743 }
1744 dex_cache->SetDexFile(dex_file.get());
1745 out_dex_files->push_back(std::move(dex_file));
1746 }
1747 return true;
1748}
1749
Andreas Gampe0793bec2016-12-01 11:37:33 -08001750// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1751// together and caches some intermediate results.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001752class ImageSanityChecks final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001753 public:
1754 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1755 REQUIRES_SHARED(Locks::mutator_lock_) {
1756 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001757 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1758 DCHECK(obj != nullptr);
1759 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1760 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1761 if (obj->IsClass()) {
1762 auto klass = obj->AsClass();
1763 for (ArtField& field : klass->GetIFields()) {
1764 CHECK_EQ(field.GetDeclaringClass(), klass);
1765 }
1766 for (ArtField& field : klass->GetSFields()) {
1767 CHECK_EQ(field.GetDeclaringClass(), klass);
1768 }
1769 const auto pointer_size = isc.pointer_size_;
1770 for (auto& m : klass->GetMethods(pointer_size)) {
1771 isc.SanityCheckArtMethod(&m, klass);
1772 }
1773 auto* vtable = klass->GetVTable();
1774 if (vtable != nullptr) {
1775 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
1776 }
1777 if (klass->ShouldHaveImt()) {
1778 ImTable* imt = klass->GetImt(pointer_size);
1779 for (size_t i = 0; i < ImTable::kSize; ++i) {
1780 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1781 }
1782 }
1783 if (klass->ShouldHaveEmbeddedVTable()) {
1784 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1785 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1786 }
1787 }
1788 mirror::IfTable* iftable = klass->GetIfTable();
1789 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1790 if (iftable->GetMethodArrayCount(i) > 0) {
1791 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1792 }
1793 }
1794 }
1795 };
1796 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001797 }
1798
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001799 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
1800 ClassLinker* class_linker,
1801 mirror::MethodDexCacheType* arr,
1802 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001803 REQUIRES_SHARED(Locks::mutator_lock_) {
1804 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001805 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001806 }
1807
Andreas Gampe0793bec2016-12-01 11:37:33 -08001808 private:
1809 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1810 : spaces_(heap->GetBootImageSpaces()),
1811 pointer_size_(class_linker->GetImagePointerSize()) {
1812 space_begin_.reserve(spaces_.size());
1813 method_sections_.reserve(spaces_.size());
1814 runtime_method_sections_.reserve(spaces_.size());
1815 for (gc::space::ImageSpace* space : spaces_) {
1816 space_begin_.push_back(space->Begin());
1817 auto& header = space->GetImageHeader();
1818 method_sections_.push_back(&header.GetMethodsSection());
1819 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1820 }
1821 }
1822
1823 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1824 REQUIRES_SHARED(Locks::mutator_lock_) {
1825 if (m->IsRuntimeMethod()) {
1826 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1827 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1828 } else if (m->IsCopied()) {
1829 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1830 } else if (expected_class != nullptr) {
1831 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1832 }
1833 if (!spaces_.empty()) {
1834 bool contains = false;
1835 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1836 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1837 contains = method_sections_[i]->Contains(offset) ||
1838 runtime_method_sections_[i]->Contains(offset);
1839 }
1840 CHECK(contains) << m << " not found";
1841 }
1842 }
1843
1844 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1845 ObjPtr<mirror::Class> expected_class)
1846 REQUIRES_SHARED(Locks::mutator_lock_) {
1847 CHECK(arr != nullptr);
1848 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1849 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1850 // expected_class == null means we are a dex cache.
1851 if (expected_class != nullptr) {
1852 CHECK(method != nullptr);
1853 }
1854 if (method != nullptr) {
1855 SanityCheckArtMethod(method, expected_class);
1856 }
1857 }
1858 }
1859
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001860 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001861 REQUIRES_SHARED(Locks::mutator_lock_) {
1862 CHECK_EQ(arr != nullptr, size != 0u);
1863 if (arr != nullptr) {
1864 bool contains = false;
1865 for (auto space : spaces_) {
1866 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001867 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001868 contains = true;
1869 break;
1870 }
1871 }
1872 CHECK(contains);
1873 }
1874 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001875 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
1876 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08001877 // expected_class == null means we are a dex cache.
1878 if (method != nullptr) {
1879 SanityCheckArtMethod(method, nullptr);
1880 }
1881 }
1882 }
1883
1884 const std::vector<gc::space::ImageSpace*>& spaces_;
1885 const PointerSize pointer_size_;
1886
1887 // Cached sections from the spaces.
1888 std::vector<const uint8_t*> space_begin_;
1889 std::vector<const ImageSection*> method_sections_;
1890 std::vector<const ImageSection*> runtime_method_sections_;
1891};
1892
Andreas Gampebe7af222017-07-25 09:57:28 -07001893static void VerifyAppImage(const ImageHeader& header,
1894 const Handle<mirror::ClassLoader>& class_loader,
1895 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
1896 ClassTable* class_table, gc::space::ImageSpace* space)
1897 REQUIRES_SHARED(Locks::mutator_lock_) {
1898 {
1899 class VerifyClassInTableArtMethodVisitor : public ArtMethodVisitor {
1900 public:
1901 explicit VerifyClassInTableArtMethodVisitor(ClassTable* table) : table_(table) {}
1902
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001903 void Visit(ArtMethod* method) override
Andreas Gampebe7af222017-07-25 09:57:28 -07001904 REQUIRES_SHARED(Locks::mutator_lock_, Locks::classlinker_classes_lock_) {
1905 ObjPtr<mirror::Class> klass = method->GetDeclaringClass();
1906 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1907 CHECK_EQ(table_->LookupByDescriptor(klass), klass) << mirror::Class::PrettyClass(klass);
1908 }
1909 }
1910
1911 private:
1912 ClassTable* const table_;
1913 };
1914 VerifyClassInTableArtMethodVisitor visitor(class_table);
1915 header.VisitPackedArtMethods(&visitor, space->Begin(), kRuntimePointerSize);
1916 }
1917 {
1918 // Verify that all direct interfaces of classes in the class table are also resolved.
1919 std::vector<ObjPtr<mirror::Class>> classes;
1920 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1921 REQUIRES_SHARED(Locks::mutator_lock_) {
1922 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1923 classes.push_back(klass);
1924 }
1925 return true;
1926 };
1927 class_table->Visit(verify_direct_interfaces_in_table);
1928 Thread* self = Thread::Current();
1929 for (ObjPtr<mirror::Class> klass : classes) {
1930 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1931 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1932 << klass->PrettyDescriptor() << " iface #" << i;
1933 }
1934 }
1935 }
1936 // Check that all non-primitive classes in dex caches are also in the class table.
1937 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1938 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1939 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
1940 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
1941 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
1942 if (klass != nullptr && !klass->IsPrimitive()) {
1943 CHECK(class_table->Contains(klass))
1944 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
1945 }
1946 }
1947 }
1948}
1949
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001950bool ClassLinker::AddImageSpace(
1951 gc::space::ImageSpace* space,
1952 Handle<mirror::ClassLoader> class_loader,
1953 jobjectArray dex_elements,
1954 const char* dex_location,
1955 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1956 std::string* error_msg) {
1957 DCHECK(out_dex_files != nullptr);
1958 DCHECK(error_msg != nullptr);
1959 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001960 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001961 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001962 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001963 DCHECK(dex_caches_object != nullptr);
1964 Runtime* const runtime = Runtime::Current();
1965 gc::Heap* const heap = runtime->GetHeap();
1966 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001967 // Check that the image is what we are expecting.
1968 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1969 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1970 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1971 image_pointer_size_);
1972 return false;
1973 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001974 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1975 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1976 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1977 expected_image_roots,
1978 header.GetImageRoots()->GetLength());
1979 return false;
1980 }
1981 StackHandleScope<3> hs(self);
1982 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1983 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1984 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1985 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001986 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01001987 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
1988 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001989 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001990 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001991 *error_msg = StringPrintf("Expected %d class roots but got %d",
1992 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001993 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001994 return false;
1995 }
1996 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001997 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
1998 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
1999 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002000 *error_msg = "App image class roots must have pointer equality with runtime ones.";
2001 return false;
2002 }
2003 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002004 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002005 if (oat_file->GetOatHeader().GetDexFileCount() !=
2006 static_cast<uint32_t>(dex_caches->GetLength())) {
2007 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
2008 "image";
2009 return false;
2010 }
2011
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002012 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002013 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
2014 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002015 // TODO: Only store qualified paths.
2016 // If non qualified, qualify it.
Vladimir Markod1908512018-11-22 14:57:28 +00002017 dex_file_location = OatFile::ResolveRelativeEncodedDexLocation(dex_location, dex_file_location);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08002018 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
2019 dex_file_location.c_str(),
2020 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002021 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002022 return false;
2023 }
2024
2025 if (app_image) {
2026 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
2027 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00002028 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002029 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00002030 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002031 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002032 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002033 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002034 }
2035 }
2036 } else {
2037 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002038 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
2039 this,
2040 dex_cache->GetResolvedMethods(),
2041 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002042 }
2043 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00002044 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002045 }
2046 out_dex_files->push_back(std::move(dex_file));
2047 }
2048
2049 if (app_image) {
2050 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002051 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002052 // Check that the class loader resolves the same way as the ones in the image.
2053 // Image class loader [A][B][C][image dex files]
2054 // Class loader = [???][dex_elements][image dex files]
2055 // Need to ensure that [???][dex_elements] == [A][B][C].
David Brazdil05909d82018-12-06 16:25:16 +00002056 // For each class loader, PathClassLoader, the loader checks the parent first. Also the logic
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002057 // for PathClassLoader does this by looping through the array of dex files. To ensure they
2058 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
2059 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002060 if (IsBootClassLoader(soa, image_class_loader.Get())) {
2061 *error_msg = "Unexpected BootClassLoader in app image";
2062 return false;
2063 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002064 // The dex files of `class_loader` are not setup yet, so we cannot do a full comparison
2065 // of `class_loader` and `image_class_loader` in `CompareClassLoaders`. Therefore, we
2066 // special case the comparison of dex files of the two class loaders, but then do full
2067 // comparisons for their shared libraries and parent.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002068 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002069 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002070 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
2071 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
2072 if (element != nullptr) {
2073 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08002074 ObjPtr<mirror::String> name;
2075 if (GetDexPathListElementName(element, &name) && name != nullptr) {
2076 loader_dex_file_names.push_back(name);
2077 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01002078 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002079 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002080 std::string temp_error_msg;
2081 std::list<ObjPtr<mirror::String>> image_dex_file_names;
2082 bool success = GetDexFileNames(
2083 soa, image_class_loader.Get(), &image_dex_file_names, &temp_error_msg);
2084 if (success) {
2085 // Ignore the number of image dex files since we are adding those to the class loader anyways.
2086 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
2087 static_cast<size_t>(dex_caches->GetLength()));
2088 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
2089 image_dex_file_names.resize(image_count);
2090 success = success && CompareDexFiles(image_dex_file_names,
2091 loader_dex_file_names,
2092 &temp_error_msg);
2093 success = success && CompareClassLoaders(soa,
2094 image_class_loader.Get(),
2095 class_loader.Get(),
2096 /*check_dex_file_names=*/ false,
2097 &temp_error_msg);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002098 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002099 if (!success) {
2100 *error_msg = StringPrintf("Rejecting application image due to class loader mismatch: '%s'",
2101 temp_error_msg.c_str());
2102 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002103 }
2104 }
2105
2106 if (kSanityCheckObjects) {
2107 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2108 auto* dex_cache = dex_caches->Get(i);
2109 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
2110 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
2111 if (field != nullptr) {
2112 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
2113 }
2114 }
2115 }
2116 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002117 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002118 }
2119 }
2120
2121 // Set entry point to interpreter if in InterpretOnly mode.
2122 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002123 SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07002124 header.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002125 }
2126
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002127 ClassTable* class_table = nullptr;
2128 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002129 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002130 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002131 }
2132 // If we have a class table section, read it and use it for verification in
2133 // UpdateAppImageClassLoadersAndDexCaches.
2134 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002135 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002136 const bool added_class_table = class_table_section.Size() > 0u;
2137 if (added_class_table) {
2138 const uint64_t start_time2 = NanoTime();
2139 size_t read_count = 0;
2140 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2141 /*make copy*/false,
2142 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002143 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002144 }
2145 if (app_image) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07002146 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches, &temp_set);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002147
2148 {
2149 ScopedTrace trace("AppImage:UpdateClassLoaders");
2150 // Update class loader and resolved strings. If added_class_table is false, the resolved
2151 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002152 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002153 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002154 // Note: We probably don't need the read barrier unless we copy the app image objects into
2155 // the region space.
2156 ObjPtr<mirror::Class> klass(root.Read());
2157 // Do not update class loader for boot image classes where the app image
2158 // class loader is only the initiating loader but not the defining loader.
2159 // Avoid read barrier since we are comparing against null.
2160 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
2161 klass->SetClassLoader</*kCheckTransaction=*/ false>(loader);
2162 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002163 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002164 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002165
Vladimir Marko305c38b2018-02-14 11:50:07 +00002166 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002167 // Every class in the app image has initially SubtypeCheckInfo in the
2168 // Uninitialized state.
2169 //
2170 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2171 // after class initialization is complete. The app image ClassStatus as-is
2172 // are almost all ClassStatus::Initialized, and being in the
2173 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2174 //
2175 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2176 //
2177 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002178 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002179 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2180 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002181 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002182 }
2183 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002184 }
2185 if (!oat_file->GetBssGcRoots().empty()) {
2186 // Insert oat file to class table for visiting .bss GC roots.
2187 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002188 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002189
Mathieu Chartier69731002016-03-02 16:08:31 -08002190 if (added_class_table) {
2191 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2192 class_table->AddClassSet(std::move(temp_set));
2193 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002194
Mathieu Chartier69731002016-03-02 16:08:31 -08002195 if (kIsDebugBuild && app_image) {
2196 // This verification needs to happen after the classes have been added to the class loader.
2197 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002198 ScopedTrace trace("AppImage:Verify");
Andreas Gampebe7af222017-07-25 09:57:28 -07002199 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002200 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002201
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002202 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002203 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002204}
2205
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002206bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002207 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2208 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002209}
2210
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002211void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002212 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2213 // enabling tracing requires the mutator lock, there are no race conditions here.
2214 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002215 Thread* const self = Thread::Current();
2216 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002217 if (kUseReadBarrier) {
2218 // We do not track new roots for CC.
2219 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2220 kVisitRootFlagClearRootLog |
2221 kVisitRootFlagStartLoggingNewRoots |
2222 kVisitRootFlagStopLoggingNewRoots));
2223 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002224 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002225 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2226 // There is 3 GC cases to handle:
2227 // Non moving concurrent:
2228 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002229 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002230 //
2231 // Moving non-concurrent:
2232 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2233 // To prevent missing roots, this case needs to ensure that there is no
2234 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2235 // class which is in the class table.
2236 //
2237 // Moving concurrent:
2238 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2239 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002240 //
2241 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2242 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2243 // these objects.
2244 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002245 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002246 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002247 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002248 for (const ClassLoaderData& data : class_loaders_) {
2249 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2250 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2251 }
2252 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002253 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002254 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002255 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002256 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002257 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002258 // Concurrent moving GC marked new roots through the to-space invariant.
2259 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002260 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002261 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2262 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2263 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2264 if (old_ref != nullptr) {
2265 DCHECK(old_ref->IsClass());
2266 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2267 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2268 // Concurrent moving GC marked new roots through the to-space invariant.
2269 CHECK_EQ(new_ref, old_ref);
2270 }
2271 }
2272 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002273 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002274 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002275 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002276 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002277 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002278 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002279 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002280 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002281 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002282 }
2283 // We deliberately ignore the class roots in the image since we
2284 // handle image roots by using the MS/CMS rescanning of dirty cards.
2285}
2286
Brian Carlstroma663ea52011-08-19 23:33:41 -07002287// Keep in sync with InitCallback. Anything we visit, we need to
2288// reinit references to when reinitializing a ClassLinker from a
2289// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002290void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002291 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002292 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002293 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2294 // unloading if we are marking roots.
2295 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002296}
2297
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002298class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2299 public:
2300 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2301 : visitor_(visitor),
2302 done_(false) {}
2303
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002304 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002305 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002306 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002307 if (!done_ && class_table != nullptr) {
2308 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2309 if (!class_table->Visit(visitor)) {
2310 // If the visitor ClassTable returns false it means that we don't need to continue.
2311 done_ = true;
2312 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002313 }
2314 }
2315
2316 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002317 // Class visitor that limits the class visits from a ClassTable to the classes with
2318 // the provided defining class loader. This filter is used to avoid multiple visits
2319 // of the same class which can be recorded for multiple initiating class loaders.
2320 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2321 public:
2322 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2323 ClassVisitor* visitor)
2324 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2325
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002326 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002327 if (klass->GetClassLoader() != defining_class_loader_) {
2328 return true;
2329 }
2330 return (*visitor_)(klass);
2331 }
2332
2333 ObjPtr<mirror::ClassLoader> const defining_class_loader_;
2334 ClassVisitor* const visitor_;
2335 };
2336
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002337 ClassVisitor* const visitor_;
2338 // If done is true then we don't need to do any more visiting.
2339 bool done_;
2340};
2341
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002342void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002343 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002344 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2345 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002346 }
2347}
2348
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002349void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002350 Thread* const self = Thread::Current();
2351 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2352 // Not safe to have thread suspension when we are holding a lock.
2353 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002354 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002355 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002356 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002357 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002358 }
2359}
2360
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002361class GetClassesInToVector : public ClassVisitor {
2362 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002363 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002364 classes_.push_back(klass);
2365 return true;
2366 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002367 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002368};
2369
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002370class GetClassInToObjectArray : public ClassVisitor {
2371 public:
2372 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2373 : arr_(arr), index_(0) {}
2374
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002375 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002376 ++index_;
2377 if (index_ <= arr_->GetLength()) {
2378 arr_->Set(index_ - 1, klass);
2379 return true;
2380 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002381 return false;
2382 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002383
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002384 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002385 return index_ <= arr_->GetLength();
2386 }
2387
2388 private:
2389 mirror::ObjectArray<mirror::Class>* const arr_;
2390 int32_t index_;
2391};
2392
2393void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002394 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2395 // is avoiding duplicates.
2396 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002397 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002398 GetClassesInToVector accumulator;
2399 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002400 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002401 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002402 return;
2403 }
2404 }
2405 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002406 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002407 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002408 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002409 // We size the array assuming classes won't be added to the class table during the visit.
2410 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002411 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002412 size_t class_table_size;
2413 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002414 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002415 // Add 100 in case new classes get loaded when we are filling in the object array.
2416 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002417 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002418 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002419 classes.Assign(
2420 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002421 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002422 GetClassInToObjectArray accumulator(classes.Get());
2423 VisitClasses(&accumulator);
2424 if (accumulator.Succeeded()) {
2425 break;
2426 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002427 }
2428 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2429 // If the class table shrank during creation of the clases array we expect null elements. If
2430 // the class table grew then the loop repeats. If classes are created after the loop has
2431 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002432 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002433 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002434 return;
2435 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002436 }
2437 }
2438}
2439
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002440ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002441 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002442 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002443 // CHA unloading analysis is not needed. No negative consequences are expected because
2444 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002445 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002446 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002447 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002448}
2449
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002450void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002451 Runtime* const runtime = Runtime::Current();
2452 JavaVMExt* const vm = runtime->GetJavaVM();
2453 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002454 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002455 if (runtime->GetJit() != nullptr) {
2456 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2457 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002458 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002459 code_cache->RemoveMethodsIn(self, *data.allocator);
2460 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002461 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002462 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002463 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002464 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002465 // Cleanup references to single implementation ArtMethods that will be deleted.
2466 if (cleanup_cha) {
2467 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2468 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2469 }
2470
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002471 delete data.allocator;
2472 delete data.class_table;
2473}
2474
Vladimir Markobcf17522018-06-01 13:14:32 +01002475ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2476 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002477 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002478 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2479 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002480}
2481
Vladimir Markobcf17522018-06-01 13:14:32 +01002482ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(/*out*/ ObjPtr<mirror::String>* out_location,
2483 Thread* self,
2484 const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002485 StackHandleScope<1> hs(self);
2486 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002487 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002488 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002489 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002490 self->AssertPendingOOMException();
2491 return nullptr;
2492 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002493 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002494 if (location == nullptr) {
2495 self->AssertPendingOOMException();
2496 return nullptr;
2497 }
2498 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002499 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002500}
2501
Vladimir Markobcf17522018-06-01 13:14:32 +01002502ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2503 const DexFile& dex_file,
2504 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002505 ObjPtr<mirror::String> location = nullptr;
2506 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002507 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002508 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002509 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002510 mirror::DexCache::InitializeDexCache(self,
2511 dex_cache,
2512 location,
2513 &dex_file,
2514 linear_alloc,
2515 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002516 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002517 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002518}
2519
Roland Levillain0e840272018-08-23 19:55:30 +01002520template <bool kMovable>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002521ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2522 ObjPtr<mirror::Class> java_lang_Class,
2523 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002524 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002525 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002526 mirror::Class::InitializeClassVisitor visitor(class_size);
Roland Levillain0e840272018-08-23 19:55:30 +01002527 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002528 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2529 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002530 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002531 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002532 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002533 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002534 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002535}
2536
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002537ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002538 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002539}
2540
Roland Levillain0e840272018-08-23 19:55:30 +01002541ObjPtr<mirror::Class> ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2542 ObjPtr<mirror::Class> java_lang_Class) {
2543 // We make this class non-movable for the unlikely case where it were to be
2544 // moved by a sticky-bit (minor) collection when using the Generational
2545 // Concurrent Copying (CC) collector, potentially creating a stale reference
2546 // in the `klass_` field of one of its instances allocated in the Large-Object
2547 // Space (LOS) -- see the comment about the dirty card scanning logic in
2548 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002549 return AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01002550 self, java_lang_Class, mirror::Array::ClassSize(image_pointer_size_));
2551}
2552
Vladimir Markobcf17522018-06-01 13:14:32 +01002553ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002554 Thread* self,
2555 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002556 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002557 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002558}
2559
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002560ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2561 const char* descriptor,
2562 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002563 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002564 if (kIsDebugBuild) {
2565 StackHandleScope<1> hs(self);
2566 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2567 Thread::PoisonObjectPointersIfDebug();
2568 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002569
2570 // For temporary classes we must wait for them to be retired.
2571 if (init_done_ && klass->IsTemp()) {
2572 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002573 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002574 ThrowEarlierClassFailure(klass);
2575 return nullptr;
2576 }
2577 StackHandleScope<1> hs(self);
2578 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2579 ObjectLock<mirror::Class> lock(self, h_class);
2580 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002581 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002582 lock.WaitIgnoringInterrupts();
2583 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002584 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002585 ThrowEarlierClassFailure(h_class.Get());
2586 return nullptr;
2587 }
2588 CHECK(h_class->IsRetired());
2589 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002590 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002591 }
2592
Brian Carlstromaded5f72011-10-07 17:15:04 -07002593 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002594 size_t index = 0;
2595 // Maximum number of yield iterations until we start sleeping.
2596 static const size_t kNumYieldIterations = 1000;
2597 // How long each sleep is in us.
2598 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002599 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002600 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002601 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002602 {
2603 ObjectTryLock<mirror::Class> lock(self, h_class);
2604 // Can not use a monitor wait here since it may block when returning and deadlock if another
2605 // thread has locked klass.
2606 if (lock.Acquired()) {
2607 // Check for circular dependencies between classes, the lock is required for SetStatus.
2608 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2609 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002610 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002611 return nullptr;
2612 }
2613 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002614 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002615 {
2616 // Handle wrapper deals with klass moving.
2617 ScopedThreadSuspension sts(self, kSuspended);
2618 if (index < kNumYieldIterations) {
2619 sched_yield();
2620 } else {
2621 usleep(kSleepDurationUS);
2622 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002623 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002624 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002625 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002626
Vladimir Marko72ab6842017-01-20 19:32:50 +00002627 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002628 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002629 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002630 }
2631 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002632 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002633 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002634 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002635}
2636
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002637using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002638
2639// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002640ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002641 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002642 for (const DexFile* dex_file : class_path) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002643 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002644 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002645 return ClassPathEntry(dex_file, dex_class_def);
2646 }
2647 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002648 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002649}
2650
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002651bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2652 Thread* self,
2653 const char* descriptor,
2654 size_t hash,
2655 Handle<mirror::ClassLoader> class_loader,
2656 /*out*/ ObjPtr<mirror::Class>* result) {
2657 ArtField* field =
2658 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2659 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2660 if (raw_shared_libraries == nullptr) {
2661 return true;
2662 }
2663
2664 StackHandleScope<2> hs(self);
2665 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2666 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2667 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
2668 for (int32_t i = 0; i < shared_libraries->GetLength(); ++i) {
2669 temp_loader.Assign(shared_libraries->Get(i));
2670 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2671 return false; // One of the shared libraries is not supported.
2672 }
2673 if (*result != nullptr) {
2674 return true; // Found the class up the chain.
2675 }
2676 }
2677 return true;
2678}
2679
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002680bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2681 Thread* self,
2682 const char* descriptor,
2683 size_t hash,
2684 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002685 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002686 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002687 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002688 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002689 return true;
2690 }
2691
David Brazdil05909d82018-12-06 16:25:16 +00002692 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002693 // For regular path or dex class loader the search order is:
2694 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002695 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002696 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002697
Calin Juravlecdd49122017-07-05 20:09:53 -07002698 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2699 StackHandleScope<1> hs(self);
2700 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2701 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2702 return false; // One of the parents is not supported.
2703 }
2704 if (*result != nullptr) {
2705 return true; // Found the class up the chain.
2706 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002707
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002708 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2709 return false; // One of the shared library loader is not supported.
2710 }
2711 if (*result != nullptr) {
2712 return true; // Found the class in a shared library.
2713 }
2714
Calin Juravlecdd49122017-07-05 20:09:53 -07002715 // Search the current class loader classpath.
2716 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampef865ea92015-04-13 22:14:19 -07002717 return true;
2718 }
2719
Calin Juravlecdd49122017-07-05 20:09:53 -07002720 if (IsDelegateLastClassLoader(soa, class_loader)) {
2721 // For delegate last, the search order is:
2722 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002723 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002724 // - class loader dex files
2725 // - parent
2726 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2727 if (*result != nullptr) {
2728 return true; // The class is part of the boot class path.
2729 }
2730
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002731 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2732 return false; // One of the shared library loader is not supported.
2733 }
2734 if (*result != nullptr) {
2735 return true; // Found the class in a shared library.
2736 }
2737
Calin Juravlecdd49122017-07-05 20:09:53 -07002738 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2739 if (*result != nullptr) {
2740 return true; // Found the class in the current class loader
2741 }
2742
2743 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2744 StackHandleScope<1> hs(self);
2745 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2746 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2747 }
2748
2749 // Unsupported class loader.
2750 *result = nullptr;
2751 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002752}
2753
2754// Finds the class in the boot class loader.
2755// If the class is found the method returns the resolved class. Otherwise it returns null.
2756ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2757 const char* descriptor,
2758 size_t hash) {
2759 ObjPtr<mirror::Class> result = nullptr;
2760 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2761 if (pair.second != nullptr) {
2762 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2763 if (klass != nullptr) {
2764 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002765 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002766 result = DefineClass(self,
2767 descriptor,
2768 hash,
2769 ScopedNullHandle<mirror::ClassLoader>(),
2770 *pair.first,
2771 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002772 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002773 if (result == nullptr) {
2774 CHECK(self->IsExceptionPending()) << descriptor;
2775 self->ClearException();
Andreas Gampef865ea92015-04-13 22:14:19 -07002776 }
2777 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002778 return result;
2779}
Andreas Gampef865ea92015-04-13 22:14:19 -07002780
Calin Juravle415dc3d2017-06-28 11:03:12 -07002781ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2782 ScopedObjectAccessAlreadyRunnable& soa,
2783 const char* descriptor,
2784 size_t hash,
2785 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00002786 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2787 IsInMemoryDexClassLoader(soa, class_loader) ||
2788 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002789 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002790
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002791 ObjPtr<mirror::Class> ret;
2792 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002793 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002794 if (dex_class_def != nullptr) {
2795 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2796 descriptor,
2797 hash,
2798 class_loader,
2799 *cp_dex_file,
2800 *dex_class_def);
2801 if (klass == nullptr) {
2802 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
2803 soa.Self()->ClearException();
2804 // TODO: Is it really right to break here, and not check the other dex files?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002805 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002806 ret = klass;
2807 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002808 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002809 return true; // Continue with the next DexFile.
2810 };
2811
2812 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2813 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002814}
2815
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002816ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2817 const char* descriptor,
2818 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002819 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002820 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002821 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002822 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002823 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002824 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2825 // for primitive classes that aren't backed by dex files.
2826 return FindPrimitiveClass(descriptor[0]);
2827 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002828 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002829 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002830 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002831 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002832 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002833 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002834 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002835 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002836 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002837 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002838 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002839 return DefineClass(self,
2840 descriptor,
2841 hash,
2842 ScopedNullHandle<mirror::ClassLoader>(),
2843 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002844 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002845 } else {
2846 // The boot class loader is searched ahead of the application class loader, failures are
2847 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2848 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002849 ObjPtr<mirror::Throwable> pre_allocated =
2850 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002851 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002852 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002853 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002854 }
2855 ObjPtr<mirror::Class> result_ptr;
2856 bool descriptor_equals;
2857 if (descriptor[0] == '[') {
2858 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2859 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2860 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2861 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002862 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002863 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002864 bool known_hierarchy =
2865 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2866 if (result_ptr != nullptr) {
2867 // The chain was understood and we found the class. We still need to add the class to
2868 // the class table to protect from racy programs that can try and redefine the path list
2869 // which would change the Class<?> returned for subsequent evaluation of const-class.
2870 DCHECK(known_hierarchy);
2871 DCHECK(result_ptr->DescriptorEquals(descriptor));
2872 descriptor_equals = true;
2873 } else {
2874 // Either the chain wasn't understood or the class wasn't found.
2875 //
2876 // If the chain was understood but we did not find the class, let the Java-side
2877 // rediscover all this and throw the exception with the right stack trace. Note that
2878 // the Java-side could still succeed for racy programs if another thread is actively
2879 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002880
Alex Light185a4612018-10-04 15:54:25 -07002881 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002882 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002883 // Oops, we can't call into java so we can't run actual class-loader code.
2884 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002885 ObjPtr<mirror::Throwable> pre_allocated =
2886 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2887 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002888 return nullptr;
2889 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002890
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002891 // Inlined DescriptorToDot(descriptor) with extra validation.
2892 //
2893 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2894 // the DescriptorEquals() check below and give a confusing error message. For example,
2895 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2896 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2897 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2898 size_t descriptor_length = strlen(descriptor);
2899 if (UNLIKELY(descriptor[0] != 'L') ||
2900 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2901 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2902 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2903 return nullptr;
2904 }
2905 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2906 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
2907
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002908 ScopedLocalRef<jobject> class_loader_object(
2909 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002910 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2911 {
2912 ScopedThreadStateChange tsc(self, kNative);
2913 ScopedLocalRef<jobject> class_name_object(
2914 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2915 if (class_name_object.get() == nullptr) {
2916 DCHECK(self->IsExceptionPending()); // OOME.
2917 return nullptr;
2918 }
2919 CHECK(class_loader_object.get() != nullptr);
2920 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2921 WellKnownClasses::java_lang_ClassLoader_loadClass,
2922 class_name_object.get()));
2923 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002924 if (result.get() == nullptr && !self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002925 // broken loader - throw NPE to be compatible with Dalvik
2926 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2927 class_name_string.c_str()).c_str());
2928 return nullptr;
2929 }
2930 result_ptr = soa.Decode<mirror::Class>(result.get());
2931 // Check the name of the returned class.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002932 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002933 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002934 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002935
2936 if (self->IsExceptionPending()) {
2937 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2938 // However, to comply with the RI behavior, first check if another thread succeeded.
2939 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2940 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2941 self->ClearException();
2942 return EnsureResolved(self, descriptor, result_ptr);
2943 }
2944 return nullptr;
2945 }
2946
2947 // Try to insert the class to the class table, checking for mismatch.
2948 ObjPtr<mirror::Class> old;
2949 {
2950 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2951 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2952 old = class_table->Lookup(descriptor, hash);
2953 if (old == nullptr) {
2954 old = result_ptr; // For the comparison below, after releasing the lock.
2955 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01002956 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07002957 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002958 } // else throw below, after releasing the lock.
2959 }
2960 }
2961 if (UNLIKELY(old != result_ptr)) {
2962 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2963 // capable class loaders. (All class loaders are considered parallel capable on Android.)
2964 mirror::Class* loader_class = class_loader->GetClass();
2965 const char* loader_class_name =
2966 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2967 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2968 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2969 << DescriptorToDot(descriptor) << "\").";
2970 return EnsureResolved(self, descriptor, old);
2971 }
2972 if (UNLIKELY(!descriptor_equals)) {
2973 std::string result_storage;
2974 const char* result_name = result_ptr->GetDescriptor(&result_storage);
2975 std::string loader_storage;
2976 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
2977 ThrowNoClassDefFoundError(
2978 "Initiating class loader of type %s returned class %s instead of %s.",
2979 DescriptorToDot(loader_class_name).c_str(),
2980 DescriptorToDot(result_name).c_str(),
2981 DescriptorToDot(descriptor).c_str());
2982 return nullptr;
2983 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002984 // Success.
2985 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002986}
2987
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002988ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
2989 const char* descriptor,
2990 size_t hash,
2991 Handle<mirror::ClassLoader> class_loader,
2992 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002993 const dex::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002994 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002995 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002996
Brian Carlstromaded5f72011-10-07 17:15:04 -07002997 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002998 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002999 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003000 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003001 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003002 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003003 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003004 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003005 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003006 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003007 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003008 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003009 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003010 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003011 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003012 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003013 }
3014
Alex Lighte9f61032018-09-24 16:04:51 -07003015 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3016 // code to be executed. We put it up here so we can avoid all the allocations associated with
3017 // creating the class. This can happen with (eg) jit threads.
3018 if (!self->CanLoadClasses()) {
3019 // Make sure we don't try to load anything, potentially causing an infinite loop.
3020 ObjPtr<mirror::Throwable> pre_allocated =
3021 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3022 self->SetException(pre_allocated);
3023 return nullptr;
3024 }
3025
Andreas Gampefa4333d2017-02-14 11:10:34 -08003026 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003027 // Allocate a class with the status of not ready.
3028 // Interface object should get the right size here. Regular class will
3029 // figure out the right size later and be replaced with one of the right
3030 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00003031 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003032 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003033 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003034 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07003035 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003036 }
Alex Lightb0f11922017-01-23 14:25:17 -08003037 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3038 // nothing.
3039 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003040 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003041 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3042 // will only be called once.
3043 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3044 klass,
3045 class_loader,
3046 dex_file,
3047 dex_class_def,
3048 &new_dex_file,
3049 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003050 // Check to see if an exception happened during runtime callbacks. Return if so.
3051 if (self->IsExceptionPending()) {
3052 return nullptr;
3053 }
Alex Lightb0f11922017-01-23 14:25:17 -08003054 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003055 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003056 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003057 return nullptr;
3058 }
3059 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003060 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003061
Jeff Hao848f70a2014-01-15 13:49:50 -08003062 // Mark the string class by setting its access flag.
3063 if (UNLIKELY(!init_done_)) {
3064 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3065 klass->SetStringClass();
3066 }
3067 }
3068
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003069 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003070 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003071 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003072 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003073
Mathieu Chartier590fee92013-09-13 13:46:47 -07003074 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003075 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003076 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003077 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3078 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003079 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003080 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003081
Mathieu Chartierc7853442015-03-27 14:35:38 -07003082 // Load the fields and other things after we are inserted in the table. This is so that we don't
3083 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3084 // other reason is that the field roots are only visited from the class table. So we need to be
3085 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003086 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003087 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003088 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003089 // An exception occured during load, set status to erroneous while holding klass' lock in case
3090 // notification is necessary.
3091 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003092 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003093 }
3094 return nullptr;
3095 }
3096
Brian Carlstromaded5f72011-10-07 17:15:04 -07003097 // Finish loading (if necessary) by finding parents
3098 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003099 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003100 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003101 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003102 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003103 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003104 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003105 }
3106 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003107
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003108 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003109 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003110 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003111
Brian Carlstromaded5f72011-10-07 17:15:04 -07003112 // Link the class (if necessary)
3113 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003114 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003115 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003116
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003117 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003118 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003119 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003120 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003121 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003122 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003123 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003124 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003125 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003126 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003127 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003128
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003129 // Instrumentation may have updated entrypoints for all methods of all
3130 // classes. However it could not update methods of this class while we
3131 // were loading it. Now the class is resolved, we can update entrypoints
3132 // as required by instrumentation.
3133 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3134 // We must be in the kRunnable state to prevent instrumentation from
3135 // suspending all threads to update entrypoints while we are doing it
3136 // for this class.
3137 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003138 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003139 }
3140
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003141 /*
3142 * We send CLASS_PREPARE events to the debugger from here. The
3143 * definition of "preparation" is creating the static fields for a
3144 * class and initializing them to the standard default values, but not
3145 * executing any code (that comes later, during "initialization").
3146 *
3147 * We did the static preparation in LinkClass.
3148 *
3149 * The class has been prepared and resolved but possibly not yet verified
3150 * at this point.
3151 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003152 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003153
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003154 // Notify native debugger of the new class and its layout.
3155 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3156
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003157 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003158}
3159
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003160uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003161 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003162 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003163 size_t num_8 = 0;
3164 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003165 size_t num_32 = 0;
3166 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003167 ClassAccessor accessor(dex_file, dex_class_def);
3168 // We allow duplicate definitions of the same field in a class_data_item
3169 // but ignore the repeated indexes here, b/21868015.
3170 uint32_t last_field_idx = dex::kDexNoIndex;
3171 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3172 uint32_t field_idx = field.GetIndex();
3173 // Ordering enforced by DexFileVerifier.
3174 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3175 if (UNLIKELY(field_idx == last_field_idx)) {
3176 continue;
3177 }
3178 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003179 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003180 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3181 char c = descriptor[0];
3182 switch (c) {
3183 case 'L':
3184 case '[':
3185 num_ref++;
3186 break;
3187 case 'J':
3188 case 'D':
3189 num_64++;
3190 break;
3191 case 'I':
3192 case 'F':
3193 num_32++;
3194 break;
3195 case 'S':
3196 case 'C':
3197 num_16++;
3198 break;
3199 case 'B':
3200 case 'Z':
3201 num_8++;
3202 break;
3203 default:
3204 LOG(FATAL) << "Unknown descriptor: " << c;
3205 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003206 }
3207 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003208 return mirror::Class::ComputeClassSize(false,
3209 0,
3210 num_8,
3211 num_16,
3212 num_32,
3213 num_64,
3214 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003215 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003216}
3217
Alex Lightfc49fec2018-01-16 22:28:36 +00003218// Special case to get oat code without overwriting a trampoline.
3219const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003220 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003221 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003222 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003223 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003224 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
3225 if (code != nullptr) {
3226 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003227 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003228 if (method->IsNative()) {
3229 // No code and native? Use generic trampoline.
3230 return GetQuickGenericJniStub();
3231 }
3232 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003233}
3234
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003235bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003236 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003237 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3238 return false;
3239 }
3240
Elliott Hughes956af0f2014-12-11 14:34:28 -08003241 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003242 return true;
3243 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003244
3245 Runtime* runtime = Runtime::Current();
3246 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3247 if (instr->InterpretOnly()) {
3248 return true;
3249 }
3250
3251 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3252 // Doing this check avoids doing compiled/interpreter transitions.
3253 return true;
3254 }
3255
3256 if (Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
3257 // Force the use of interpreter when it is required by the debugger.
3258 return true;
3259 }
3260
Alex Light8f34aba2017-10-09 13:46:32 -07003261 if (Thread::Current()->IsAsyncExceptionPending()) {
3262 // Force use of interpreter to handle async-exceptions
3263 return true;
3264 }
3265
Alex Light2d441b12018-06-08 15:33:21 -07003266 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3267 const void* instr_target = instr->GetCodeForInvoke(method);
3268 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3269 return ShouldUseInterpreterEntrypoint(method, instr_target);
3270 }
3271
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003272 if (runtime->IsJavaDebuggable()) {
3273 // For simplicity, we ignore precompiled code and go to the interpreter
3274 // assuming we don't already have jitted code.
3275 // We could look at the oat file where `quick_code` is being defined,
3276 // and check whether it's been compiled debuggable, but we decided to
3277 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003278 jit::Jit* jit = Runtime::Current()->GetJit();
3279 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3280 }
3281
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003282 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003283 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003284 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003285 // since we want to JIT it (at first use) with extra stackmaps for native
3286 // debugging. We keep however all AOT code from the boot image,
3287 // since the JIT-at-first-use is blocking and would result in non-negligible
3288 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003289 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003290 }
3291
3292 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003293}
3294
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003295void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003296 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
David Sehr709b0702016-10-13 09:12:37 -07003297 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07003298 if (klass->NumDirectMethods() == 0) {
3299 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003300 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003301 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003302 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003303 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003304 return; // OAT file unavailable.
3305 }
Ian Rogers19846512012-02-24 11:42:47 -08003306 }
Alex Light64ad14d2014-08-19 14:23:13 -07003307
Mathieu Chartierf8322842014-05-16 10:59:25 -07003308 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartier18e26872018-06-04 17:19:02 -07003309 const uint16_t class_def_idx = klass->GetDexClassDefIndex();
3310 CHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
3311 ClassAccessor accessor(dex_file, class_def_idx);
Ian Rogers1c829822013-09-30 18:18:50 -07003312 // There should always be class data if there were direct methods.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003313 CHECK(accessor.HasClassData()) << klass->PrettyDescriptor();
Ian Rogers97b52f82014-08-14 11:34:07 -07003314 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003315 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3316 klass->GetDexClassDefIndex(),
3317 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003318 // Link the code of methods skipped by LinkCode.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003319 for (size_t method_index = 0; method_index < accessor.NumDirectMethods(); ++method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003320 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003321 if (!method->IsStatic()) {
3322 // Only update static methods.
3323 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003324 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003325 const void* quick_code = nullptr;
3326 if (has_oat_class) {
3327 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003328 quick_code = oat_method.GetQuickCode();
3329 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003330 // Check whether the method is native, in which case it's generic JNI.
3331 if (quick_code == nullptr && method->IsNative()) {
3332 quick_code = GetQuickGenericJniStub();
3333 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003334 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003335 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003336 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003337 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003338 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003339 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003340}
3341
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003342// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3343// method. Should only be called on non-invokable methods.
3344inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003345 DCHECK(method != nullptr);
3346 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003347 method->SetEntryPointFromQuickCompiledCodePtrSize(
3348 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3349 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003350}
3351
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003352static void LinkCode(ClassLinker* class_linker,
3353 ArtMethod* method,
3354 const OatFile::OatClass* oat_class,
3355 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003356 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003357 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003358 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003359 // The following code only applies to a non-compiler runtime.
3360 return;
3361 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003362 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003363 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003364 if (oat_class != nullptr) {
3365 // Every kind of method should at least get an invoke stub from the oat_method.
3366 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003367 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003368 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003369 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003370
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003371 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003372 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003373 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003374
Alex Light9139e002015-10-09 15:59:48 -07003375 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003376 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003377 return;
3378 }
Ian Rogers19846512012-02-24 11:42:47 -08003379
3380 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003381 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003382 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3383 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003384 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003385 } else if (quick_code == nullptr && method->IsNative()) {
3386 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003387 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003388 // Set entry point from compiled code if there's no code or in interpreter only mode.
3389 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003390 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003391
Ian Rogers62d6c772013-02-27 08:32:07 -08003392 if (method->IsNative()) {
3393 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003394 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003395
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003396 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003397 // We have a native method here without code. Then it should have either the generic JNI
3398 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3399 // TODO: this doesn't handle all the cases where trampolines may be installed.
3400 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003401 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3402 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003403 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003404 }
3405}
3406
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003407void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003408 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003409 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003410 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003411 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003412 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003413 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003414 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003415 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003416
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003417 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003418 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003419 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003420 klass->SetAccessFlags(access_flags);
3421 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003422 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003423 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003424
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003425 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003426 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003427}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003428
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003429LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3430 LinearAlloc* allocator,
3431 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003432 if (length == 0) {
3433 return nullptr;
3434 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003435 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3436 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3437 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003438 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003439 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003440 CHECK(ret != nullptr);
3441 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3442 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003443}
3444
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003445LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3446 LinearAlloc* allocator,
3447 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003448 if (length == 0) {
3449 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003450 }
Vladimir Marko14632852015-08-17 12:07:23 +01003451 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3452 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003453 const size_t storage_size =
3454 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003455 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003456 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003457 CHECK(ret != nullptr);
3458 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003459 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003460 }
3461 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003462}
3463
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003464LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003465 if (class_loader == nullptr) {
3466 return Runtime::Current()->GetLinearAlloc();
3467 }
3468 LinearAlloc* allocator = class_loader->GetAllocator();
3469 DCHECK(allocator != nullptr);
3470 return allocator;
3471}
3472
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003473LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003474 if (class_loader == nullptr) {
3475 return Runtime::Current()->GetLinearAlloc();
3476 }
3477 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3478 LinearAlloc* allocator = class_loader->GetAllocator();
3479 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003480 RegisterClassLoader(class_loader);
3481 allocator = class_loader->GetAllocator();
3482 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003483 }
3484 return allocator;
3485}
3486
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003487void ClassLinker::LoadClass(Thread* self,
3488 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003489 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003490 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003491 ClassAccessor accessor(dex_file,
3492 dex_class_def,
3493 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003494 if (!accessor.HasClassData()) {
3495 return;
3496 }
3497 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003498 {
3499 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3500 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003501 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003502 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003503 // We allow duplicate definitions of the same field in a class_data_item
3504 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003505 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003506 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3507 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003508 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003509 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3510 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003511 accessor.NumInstanceFields());
3512 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003513 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003514 uint32_t last_static_field_idx = 0u;
3515 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003516
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003517 // Methods
3518 bool has_oat_class = false;
3519 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3520 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3521 : OatFile::OatClass::Invalid();
3522 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3523 klass->SetMethodsPtr(
3524 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3525 accessor.NumDirectMethods(),
3526 accessor.NumVirtualMethods());
3527 size_t class_def_method_index = 0;
3528 uint32_t last_dex_method_index = dex::kDexNoIndex;
3529 size_t last_class_def_method_index = 0;
3530
3531 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3532 // methods needs to decode all of the fields.
3533 accessor.VisitFieldsAndMethods([&](
3534 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3535 uint32_t field_idx = field.GetIndex();
3536 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3537 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3538 LoadField(field, klass, &sfields->At(num_sfields));
3539 ++num_sfields;
3540 last_static_field_idx = field_idx;
3541 }
3542 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3543 uint32_t field_idx = field.GetIndex();
3544 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3545 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3546 LoadField(field, klass, &ifields->At(num_ifields));
3547 ++num_ifields;
3548 last_instance_field_idx = field_idx;
3549 }
3550 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3551 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3552 image_pointer_size_);
3553 LoadMethod(dex_file, method, klass, art_method);
3554 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3555 uint32_t it_method_index = method.GetIndex();
3556 if (last_dex_method_index == it_method_index) {
3557 // duplicate case
3558 art_method->SetMethodIndex(last_class_def_method_index);
3559 } else {
3560 art_method->SetMethodIndex(class_def_method_index);
3561 last_dex_method_index = it_method_index;
3562 last_class_def_method_index = class_def_method_index;
3563 }
3564 ++class_def_method_index;
3565 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3566 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3567 class_def_method_index - accessor.NumDirectMethods(),
3568 image_pointer_size_);
3569 LoadMethod(dex_file, method, klass, art_method);
3570 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3571 ++class_def_method_index;
3572 });
3573
3574 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003575 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003576 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3577 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3578 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003579 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3580 if (sfields != nullptr) {
3581 sfields->SetSize(num_sfields);
3582 }
3583 if (ifields != nullptr) {
3584 ifields->SetSize(num_ifields);
3585 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003586 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003587 // Set the field arrays.
3588 klass->SetSFieldsPtr(sfields);
3589 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003590 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003591 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003592 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003593 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003594 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003595 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003596}
3597
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003598void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003599 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003600 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003601 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003602 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003603 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003604
David Brazdil85865692018-10-30 17:26:20 +00003605 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3606 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003607}
3608
Mathieu Chartier268764d2016-09-13 12:09:38 -07003609void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003610 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003611 Handle<mirror::Class> klass,
3612 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003613 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003614 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003615 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003616
Mathieu Chartier268764d2016-09-13 12:09:38 -07003617 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003618 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003619 dst->SetDeclaringClass(klass.Get());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003620 dst->SetCodeItemOffset(method.GetCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003621
David Brazdil85865692018-10-30 17:26:20 +00003622 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3623 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003624
Ian Rogersdfb325e2013-10-30 01:00:44 -07003625 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003626 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003627 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3628 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003629 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003630 klass->SetFinalizable();
3631 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003632 std::string temp;
3633 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003634 // The Enum class declares a "final" finalize() method to prevent subclasses from
3635 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3636 // subclasses, so we exclude it here.
3637 // We also want to avoid setting the flag on Object, where we know that finalize() is
3638 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003639 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3640 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003641 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003642 }
3643 }
3644 }
3645 } else if (method_name[0] == '<') {
3646 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003647 bool is_init = (strcmp("<init>", method_name) == 0);
3648 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003649 if (UNLIKELY(!is_init && !is_clinit)) {
3650 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3651 } else {
3652 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3653 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003654 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003655 access_flags |= kAccConstructor;
3656 }
3657 }
3658 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003659 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3660 // Check if the native method is annotated with @FastNative or @CriticalNative.
3661 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3662 dex_file, dst->GetClassDef(), dex_method_idx);
3663 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003664 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003665 // Must be done after SetAccessFlags since IsAbstract depends on it.
3666 if (klass->IsInterface() && dst->IsAbstract()) {
3667 dst->CalculateAndSetImtIndex();
3668 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003669}
3670
Ian Rogers7b078e82014-09-10 14:44:24 -07003671void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003672 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003673 self,
3674 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003675 Runtime::Current()->GetLinearAlloc());
3676 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003677 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003678}
3679
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003680void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003681 ObjPtr<mirror::DexCache> dex_cache) {
3682 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003683 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003684 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003685 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003686}
3687
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003688void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003689 ObjPtr<mirror::DexCache> dex_cache,
3690 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003691 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003692 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003693 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003694 // For app images, the dex cache location may be a suffix of the dex file location since the
3695 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003696 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3697 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003698 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3699 std::string dex_file_location = dex_file.GetLocation();
3700 CHECK_GE(dex_file_location.length(), dex_cache_length)
Mathieu Chartier76172162016-01-26 14:54:06 -08003701 << dex_cache_location << " " << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003702 // Take suffix.
3703 const std::string dex_file_suffix = dex_file_location.substr(
3704 dex_file_location.length() - dex_cache_length,
3705 dex_cache_length);
3706 // Example dex_cache location is SettingsProvider.apk and
3707 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
Mathieu Chartier76172162016-01-26 14:54:06 -08003708 CHECK_EQ(dex_cache_location, dex_file_suffix);
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003709 const OatFile* oat_file =
3710 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003711 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3712 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3713 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3714 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003715 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003716 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3717 DexCacheData data = *it;
3718 if (self->IsJWeakCleared(data.weak_root)) {
3719 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003720 it = dex_caches_.erase(it);
3721 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003722 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003723 it->dex_file->GetOatDexFile() != nullptr &&
3724 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003725 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003726 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003727 ++it;
3728 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003729 }
Vladimir Markob066d432018-01-03 13:14:37 +00003730 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003731 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003732 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003733 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003734 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003735 DexCacheData data;
3736 data.weak_root = dex_cache_jweak;
3737 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003738 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003739 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003740 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003741 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3742 // path dex caches without an image.
3743 data.class_table->InsertStrongRoot(dex_cache);
3744 if (class_loader != nullptr) {
3745 // Since we added a strong root to the class table, do the write barrier as required for
3746 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003747 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003748 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003749 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003750}
3751
Vladimir Markocd556b02017-02-03 11:47:34 +00003752ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3753 return data.IsValid()
3754 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3755 : nullptr;
3756}
3757
3758ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3759 Thread* self,
3760 ObjPtr<mirror::DexCache> dex_cache,
3761 const DexCacheData& data,
3762 ObjPtr<mirror::ClassLoader> class_loader) {
3763 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3764 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3765 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3766 "Attempt to register dex file %s with multiple class loaders",
3767 data.dex_file->GetLocation().c_str());
3768 return nullptr;
3769 }
3770 return dex_cache;
3771}
3772
Alex Light07f06212017-06-01 14:01:43 -07003773void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3774 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003775 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003776 Thread* self = Thread::Current();
3777 StackHandleScope<2> hs(self);
3778 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3779 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3780 const DexFile* dex_file = dex_cache->GetDexFile();
3781 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3782 if (kIsDebugBuild) {
3783 DexCacheData old_data;
3784 {
3785 ReaderMutexLock mu(self, *Locks::dex_lock_);
3786 old_data = FindDexCacheDataLocked(*dex_file);
3787 }
3788 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3789 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3790 << "been registered on dex file " << dex_file->GetLocation();
3791 }
3792 ClassTable* table;
3793 {
3794 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3795 table = InsertClassTableForClassLoader(h_class_loader.Get());
3796 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003797 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3798 // a thread holding the dex lock and blocking on a condition variable regarding
3799 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003800 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003801 WriterMutexLock mu(self, *Locks::dex_lock_);
3802 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3803 table->InsertStrongRoot(h_dex_cache.Get());
3804 if (h_class_loader.Get() != nullptr) {
3805 // Since we added a strong root to the class table, do the write barrier as required for
3806 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003807 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003808 }
3809}
3810
Vladimir Markocd556b02017-02-03 11:47:34 +00003811ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3812 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003813 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003814 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003815 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003816 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003817 old_data = FindDexCacheDataLocked(dex_file);
3818 }
3819 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3820 if (old_dex_cache != nullptr) {
3821 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003822 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003823 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003824 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3825 DCHECK(linear_alloc != nullptr);
3826 ClassTable* table;
3827 {
3828 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3829 table = InsertClassTableForClassLoader(class_loader);
3830 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003831 // Don't alloc while holding the lock, since allocation may need to
3832 // suspend all threads and another thread may need the dex_lock_ to
3833 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003834 StackHandleScope<3> hs(self);
3835 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003836 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003837 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3838 self,
3839 dex_file)));
3840 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003841 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003842 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3843 // a thread holding the dex lock and blocking on a condition variable regarding
3844 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003845 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08003846 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003847 old_data = FindDexCacheDataLocked(dex_file);
3848 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003849 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003850 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3851 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3852 // that the arrays are null.
3853 mirror::DexCache::InitializeDexCache(self,
3854 h_dex_cache.Get(),
3855 h_location.Get(),
3856 &dex_file,
3857 linear_alloc,
3858 image_pointer_size_);
3859 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003860 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003861 }
3862 if (old_dex_cache != nullptr) {
3863 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3864 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003865 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003866 self->ClearException();
3867 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3868 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3869 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003870 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003871 self->AssertPendingOOMException();
3872 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003873 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003874 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003875 if (h_class_loader.Get() != nullptr) {
3876 // Since we added a strong root to the class table, do the write barrier as required for
3877 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003878 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003879 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003880 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003881}
3882
Vladimir Markocd556b02017-02-03 11:47:34 +00003883bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003884 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003885 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003886}
3887
Vladimir Markocd556b02017-02-03 11:47:34 +00003888ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
3889 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003890 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
3891 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00003892 if (dex_cache != nullptr) {
3893 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003894 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003895 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003896 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003897 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07003898 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003899 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003900 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07003901 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
3902 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003903 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003904}
3905
Vladimir Markocd556b02017-02-03 11:47:34 +00003906ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
3907 const DexFile* dex_file = dex_cache->GetDexFile();
3908 DCHECK(dex_file != nullptr);
3909 ReaderMutexLock mu(self, *Locks::dex_lock_);
3910 // Search assuming unique-ness of dex file.
3911 for (const DexCacheData& data : dex_caches_) {
3912 // Avoid decoding (and read barriers) other unrelated dex caches.
3913 if (data.dex_file == dex_file) {
3914 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
3915 if (registered_dex_cache != nullptr) {
3916 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
3917 return data.class_table;
3918 }
3919 }
3920 }
3921 return nullptr;
3922}
3923
3924ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
3925 // Search assuming unique-ness of dex file.
3926 for (const DexCacheData& data : dex_caches_) {
3927 // Avoid decoding (and read barriers) other unrelated dex caches.
3928 if (data.dex_file == &dex_file) {
3929 return data;
3930 }
3931 }
3932 return DexCacheData();
3933}
3934
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003935ObjPtr<mirror::Class> ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01003936 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08003937 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Markoacb906d2018-05-30 10:23:49 +01003938 if (UNLIKELY(primitive_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003939 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003940 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003941 }
Ian Rogers1f539342012-10-03 21:09:42 -07003942 // Must hold lock on object when initializing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003943 StackHandleScope<1> hs(self);
3944 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003945 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003946 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3947 h_class->SetPrimitiveType(type);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003948 h_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Andreas Gampe5b20b352018-10-11 19:03:20 -07003949 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(h_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003950 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003951 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08003952 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
3953 h_class.Get(),
3954 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003955 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003956 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07003957}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003958
Vladimir Marko02610552018-06-04 14:38:00 +01003959inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
3960 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
3961}
3962
Brian Carlstrombe977852011-07-19 14:54:54 -07003963// Create an array class (i.e. the class object for the array, not the
3964// array itself). "descriptor" looks like "[C" or "[[[[B" or
3965// "[Ljava/lang/String;".
3966//
3967// If "descriptor" refers to an array of primitives, look up the
3968// primitive type's internally-generated class object.
3969//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003970// "class_loader" is the class loader of the class that's referring to
3971// us. It's used to ensure that we're looking for the element type in
3972// the right context. It does NOT become the class loader for the
3973// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003974//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07003975// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003976ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
3977 const char* descriptor,
3978 size_t hash,
3979 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003980 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003981 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003982 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07003983
3984 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3985 // code to be executed. We put it up here so we can avoid all the allocations associated with
3986 // creating the class. This can happen with (eg) jit threads.
3987 if (!self->CanLoadClasses()) {
3988 // Make sure we don't try to load anything, potentially causing an infinite loop.
3989 ObjPtr<mirror::Throwable> pre_allocated =
3990 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3991 self->SetException(pre_allocated);
3992 return nullptr;
3993 }
3994
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003995 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3996 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003997 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003998 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003999 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004000 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4001 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004002 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004003 DCHECK(self->IsExceptionPending());
4004 return nullptr;
4005 } else {
4006 self->ClearException();
4007 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004008 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004009 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4010 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4011 return nullptr;
4012 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004013 // See if the component type is already loaded. Array classes are
4014 // always associated with the class loader of their underlying
4015 // element type -- an array of Strings goes with the loader for
4016 // java/lang/String -- so we need to look for it there. (The
4017 // caller should have checked for the existence of the class
4018 // before calling here, but they did so with *their* class loader,
4019 // not the component type's loader.)
4020 //
4021 // If we find it, the caller adds "loader" to the class' initiating
4022 // loader list, which should prevent us from going through this again.
4023 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004024 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004025 // are the same, because our caller (FindClass) just did the
4026 // lookup. (Even if we get this wrong we still have correct behavior,
4027 // because we effectively do this lookup again when we add the new
4028 // class to the hash table --- necessary because of possible races with
4029 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004030 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004031 ObjPtr<mirror::Class> new_class =
4032 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004033 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004034 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004035 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004036 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004037
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004038 // Fill out the fields in the Class.
4039 //
4040 // It is possible to execute some methods against arrays, because
4041 // all arrays are subclasses of java_lang_Object_, so we need to set
4042 // up a vtable. We can just point at the one in java_lang_Object_.
4043 //
4044 // Array classes are simple enough that we don't need to do a full
4045 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004046 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004047 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004048 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004049 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004050 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Class>>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004051 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004052 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Object>>(this));
4053 } else if (strcmp(descriptor, "[Ljava/lang/String;") == 0) {
4054 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::String>>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004055 } else if (strcmp(descriptor, "[Z") == 0) {
4056 new_class.Assign(GetClassRoot<mirror::BooleanArray>(this));
4057 } else if (strcmp(descriptor, "[B") == 0) {
4058 new_class.Assign(GetClassRoot<mirror::ByteArray>(this));
4059 } else if (strcmp(descriptor, "[C") == 0) {
4060 new_class.Assign(GetClassRoot<mirror::CharArray>(this));
4061 } else if (strcmp(descriptor, "[S") == 0) {
4062 new_class.Assign(GetClassRoot<mirror::ShortArray>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004063 } else if (strcmp(descriptor, "[I") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004064 new_class.Assign(GetClassRoot<mirror::IntArray>(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07004065 } else if (strcmp(descriptor, "[J") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004066 new_class.Assign(GetClassRoot<mirror::LongArray>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004067 } else if (strcmp(descriptor, "[F") == 0) {
4068 new_class.Assign(GetClassRoot<mirror::FloatArray>(this));
4069 } else if (strcmp(descriptor, "[D") == 0) {
4070 new_class.Assign(GetClassRoot<mirror::DoubleArray>(this));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004071 }
4072 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004073 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004074 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004075 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004076 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004077 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004078 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004079 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004080 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004081 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004082 DCHECK(new_class->GetComponentType() != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004083 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004084 new_class->SetSuperClass(java_lang_Object);
4085 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004086 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004087 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07004088 if (component_type->IsPrimitive()) {
4089 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
4090 } else {
4091 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
4092 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004093 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00004094 new_class->PopulateEmbeddedVTable(image_pointer_size_);
4095 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
4096 new_class->SetImt(object_imt, image_pointer_size_);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004097 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(new_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004098 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004099 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07004100 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004101
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004102 // All arrays have java/lang/Cloneable and java/io/Serializable as
4103 // interfaces. We need to set that up here, so that stuff like
4104 // "instanceof" works right.
4105 //
4106 // Note: The GC could run during the call to FindSystemClass,
4107 // so we need to make sure the class object is GC-valid while we're in
4108 // there. Do this by clearing the interface list so the GC will just
4109 // think that the entries are null.
4110
4111
4112 // Use the single, global copies of "interfaces" and "iftable"
4113 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004114 {
Vladimir Marko02610552018-06-04 14:38:00 +01004115 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004116 CHECK(array_iftable != nullptr);
4117 new_class->SetIfTable(array_iftable);
4118 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004119
Elliott Hughes00626c22013-06-14 15:04:14 -07004120 // Inherit access flags from the component type.
4121 int access_flags = new_class->GetComponentType()->GetAccessFlags();
4122 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
4123 access_flags &= kAccJavaFlagsMask;
4124 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004125 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07004126 access_flags |= kAccAbstract | kAccFinal;
4127 access_flags &= ~kAccInterface;
Andreas Gampe5b20b352018-10-11 19:03:20 -07004128 // Arrays are access-checks-clean and preverified.
4129 access_flags |= kAccVerificationAttempted;
Elliott Hughes00626c22013-06-14 15:04:14 -07004130
4131 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004132
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004133 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004134 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004135 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4136 // duplicate events in case of races. Array classes don't really follow dedicated
4137 // load and prepare, anyways.
4138 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4139 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4140
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004141 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004142 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004143 }
4144 // Another thread must have loaded the class after we
4145 // started but before we finished. Abandon what we've
4146 // done.
4147 //
4148 // (Yes, this happens.)
4149
Vladimir Markobcf17522018-06-01 13:14:32 +01004150 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004151}
4152
Vladimir Marko9186b182018-11-06 14:55:54 +00004153ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4154 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004155 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004156 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4157 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4158 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4159 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4160 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4161 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4162 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4163 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4164 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004165 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004166 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004167 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004168 return GetClassRoot(class_root, this);
4169}
4170
4171ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4172 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4173 if (UNLIKELY(result == nullptr)) {
4174 std::string printable_type(PrintableChar(type));
4175 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4176 }
4177 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004178}
4179
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004180ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4181 ObjPtr<mirror::Class> klass,
4182 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004183 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004184 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004185 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004186 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004187 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004188 source += " from ";
4189 source += dex_cache->GetLocation()->ToModifiedUtf8();
4190 }
4191 LOG(INFO) << "Loaded class " << descriptor << source;
4192 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004193 {
4194 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004195 ObjPtr<mirror::ClassLoader> const class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004196 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004197 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004198 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004199 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004200 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004201 VerifyObject(klass);
4202 class_table->InsertWithHash(klass, hash);
4203 if (class_loader != nullptr) {
4204 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004205 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004206 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004207 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004208 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004209 }
4210 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004211 if (kIsDebugBuild) {
4212 // Test that copied methods correctly can find their holder.
4213 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4214 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4215 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004216 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004217 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004218}
4219
Vladimir Marko1998cd02017-01-13 13:02:58 +00004220void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004221 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4222 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4223 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4224 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004225 }
4226}
4227
Alex Lighte64300b2015-12-15 15:02:47 -08004228// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004229void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004230 LengthPrefixedArray<ArtMethod>* new_methods) {
4231 klass->SetMethodsPtrUnchecked(new_methods,
4232 klass->NumDirectMethods(),
4233 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004234 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004235 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004236}
4237
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004238ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4239 const char* descriptor,
4240 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004241 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4242}
4243
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004244ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4245 const char* descriptor,
4246 size_t hash,
4247 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004248 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4249 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4250 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004251 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004252 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004253 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004254 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004255 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004256 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004257}
4258
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004259class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4260 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004261 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004262
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004263 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004264 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004265 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004266 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004267 if (class_table != nullptr) {
4268 class_table->FreezeSnapshot();
4269 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004270 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004271};
4272
4273void ClassLinker::MoveClassTableToPreZygote() {
4274 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004275 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004276 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004277 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004278}
4279
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004280// Look up classes by hash and descriptor and put all matching ones in the result array.
4281class LookupClassesVisitor : public ClassLoaderVisitor {
4282 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004283 LookupClassesVisitor(const char* descriptor,
4284 size_t hash,
4285 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004286 : descriptor_(descriptor),
4287 hash_(hash),
4288 result_(result) {}
4289
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004290 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004291 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004292 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004293 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004294 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4295 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004296 result_->push_back(klass);
4297 }
4298 }
4299
4300 private:
4301 const char* const descriptor_;
4302 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004303 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004304};
4305
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004306void ClassLinker::LookupClasses(const char* descriptor,
4307 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004308 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004309 Thread* const self = Thread::Current();
4310 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004311 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004312 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004313 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004314 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004315 result.push_back(klass);
4316 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004317 LookupClassesVisitor visitor(descriptor, hash, &result);
4318 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004319}
4320
Alex Lightf1f10492015-10-07 16:08:36 -07004321bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4322 Handle<mirror::Class> klass,
4323 Handle<mirror::Class> supertype) {
4324 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004325 DCHECK(klass != nullptr);
4326 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004327
Alex Lightf1f10492015-10-07 16:08:36 -07004328 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4329 VerifyClass(self, supertype);
4330 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004331
4332 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
4333 // The supertype is either verified, or we soft failed at AOT time.
4334 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004335 return true;
4336 }
4337 // If we got this far then we have a hard failure.
4338 std::string error_msg =
4339 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004340 klass->PrettyDescriptor().c_str(),
4341 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004342 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004343 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004344 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004345 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004346 // Set during VerifyClass call (if at all).
4347 self->ClearException();
4348 }
4349 // Change into a verify error.
4350 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004351 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004352 self->GetException()->SetCause(cause.Get());
4353 }
4354 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4355 if (Runtime::Current()->IsAotCompiler()) {
4356 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4357 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004358 // Need to grab the lock to change status.
4359 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004360 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004361 return false;
4362}
4363
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004364verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004365 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004366 {
4367 // TODO: assert that the monitor on the Class is held
4368 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004369
Andreas Gampe884f3b82016-03-30 19:52:58 -07004370 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004371 ClassStatus old_status = klass->GetStatus();
4372 while (old_status == ClassStatus::kVerifying ||
4373 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004374 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004375 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4376 // case we may see the same status again. b/62912904. This is why the check is
4377 // greater or equal.
4378 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004379 << "Class '" << klass->PrettyClass()
4380 << "' performed an illegal verification state transition from " << old_status
4381 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004382 old_status = klass->GetStatus();
4383 }
jeffhao98eacac2011-09-14 16:11:53 -07004384
Andreas Gampe884f3b82016-03-30 19:52:58 -07004385 // The class might already be erroneous, for example at compile time if we attempted to verify
4386 // this class as a parent to another.
4387 if (klass->IsErroneous()) {
4388 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004389 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004390 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004391
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004392 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004393 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004394 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004395 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004396 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004397
4398 // For AOT, don't attempt to re-verify if we have already found we should
4399 // verify at runtime.
4400 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004401 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004402 }
jeffhao98eacac2011-09-14 16:11:53 -07004403
Vladimir Marko2c64a832018-01-04 11:31:56 +00004404 if (klass->GetStatus() == ClassStatus::kResolved) {
4405 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004406 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004407 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004408 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004409 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004410 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004411 }
4412
4413 // Skip verification if disabled.
4414 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004415 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004416 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004417 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004418 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004419 }
4420
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004421 VLOG(class_linker) << "Beginning verification for class: "
4422 << klass->PrettyDescriptor()
4423 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4424
Ian Rogers9ffb0392012-09-10 11:56:50 -07004425 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004426 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004427 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4428 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004429 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004430 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004431 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004432 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004433
Alex Lightf1f10492015-10-07 16:08:36 -07004434 // Verify all default super-interfaces.
4435 //
4436 // (1) Don't bother if the superclass has already had a soft verification failure.
4437 //
4438 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4439 // recursive initialization by themselves. This is because when an interface is initialized
4440 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4441 // but choose not to for an optimization. If the interfaces is being verified due to a class
4442 // initialization (which would need all the default interfaces to be verified) the class code
4443 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004444 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004445 && !klass->IsInterface()) { // See (2)
4446 int32_t iftable_count = klass->GetIfTableCount();
4447 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4448 // Loop through all interfaces this class has defined. It doesn't matter the order.
4449 for (int32_t i = 0; i < iftable_count; i++) {
4450 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004451 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004452 // We only care if we have default interfaces and can skip if we are already verified...
4453 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4454 continue;
4455 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4456 // We had a hard failure while verifying this interface. Just return immediately.
4457 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004458 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004459 } else if (UNLIKELY(!iface->IsVerified())) {
4460 // We softly failed to verify the iface. Stop checking and clean up.
4461 // Put the iface into the supertype handle so we know what caused us to fail.
4462 supertype.Assign(iface.Get());
4463 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004464 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004465 }
4466 }
4467
Alex Lightf1f10492015-10-07 16:08:36 -07004468 // At this point if verification failed, then supertype is the "first" supertype that failed
4469 // verification (without a specific order). If verification succeeded, then supertype is either
4470 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004471 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004472 supertype.Get() == klass->GetSuperClass() ||
4473 !supertype->IsVerified());
4474
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004475 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004476 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004477 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004478 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004479
4480 VLOG(class_linker) << "Class preverified status for class "
4481 << klass->PrettyDescriptor()
4482 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4483 << ": "
4484 << preverified;
4485
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004486 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4487 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004488 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4489 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004490
Ian Rogers62d6c772013-02-27 08:32:07 -08004491 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004492 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004493 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004494 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004495 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004496
4497 // Verification is done, grab the lock again.
4498 ObjectLock<mirror::Class> lock(self, klass);
4499
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004500 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4501 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004502 VLOG(class_linker) << "Soft verification failure in class "
4503 << klass->PrettyDescriptor()
4504 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4505 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004506 }
Ian Rogers1f539342012-10-03 21:09:42 -07004507 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004508 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004509 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004510 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004511 // Even though there were no verifier failures we need to respect whether the super-class and
4512 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004513 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004514 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004515 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004516 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4517 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004518 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004519 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004520 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004521 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004522 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004523 // Soft failures at compile time should be retried at runtime. Soft
4524 // failures at runtime will be handled by slow paths in the generated
4525 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004526 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004527 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004528 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004529 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004530 // As this is a fake verified status, make sure the methods are _not_ marked
4531 // kAccSkipAccessChecks later.
4532 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004533 }
4534 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004535 } else {
David Sehr709b0702016-10-13 09:12:37 -07004536 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004537 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4538 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004539 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004540 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004541 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004542 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004543 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004544 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004545 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004546 // method.
4547 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004548 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004549 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004550
4551 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4552 // Never skip access checks if the verification soft fail is forced.
4553 // Mark the class as having a verification attempt to avoid re-running the verifier.
4554 klass->SetVerificationAttempted();
4555 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004556 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004557 }
Andreas Gampe48498592014-09-10 19:48:05 -07004558 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004559 // Done verifying. Notify the compiler about the verification status, in case the class
4560 // was verified implicitly (eg super class of a compiled class).
4561 if (Runtime::Current()->IsAotCompiler()) {
4562 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4563 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4564 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004565 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004566}
4567
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004568verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4569 Handle<mirror::Class> klass,
4570 verifier::HardFailLogMode log_level,
4571 std::string* error_msg) {
4572 Runtime* const runtime = Runtime::Current();
4573 return verifier::MethodVerifier::VerifyClass(self,
4574 klass.Get(),
4575 runtime->GetCompilerCallbacks(),
4576 runtime->IsAotCompiler(),
4577 log_level,
Andreas Gampe6cc23ac2018-08-24 15:22:43 -07004578 Runtime::Current()->GetTargetSdkVersion(),
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004579 error_msg);
4580}
4581
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004582bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004583 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004584 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004585 // If we're compiling, we can only verify the class using the oat file if
4586 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004587 // the compilation unit (app - dependencies). We will let the compiler callback
4588 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004589 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004590 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004591 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004592 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004593 return false;
4594 }
4595 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004596 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004597 return false;
4598 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004599 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004600
Andreas Gampeb40d3612018-06-26 15:49:42 -07004601 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004602 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004603 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004604 return false;
4605 }
4606
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004607 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004608 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004609 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004610 return true;
4611 }
4612 // If we only verified a subset of the classes at compile time, we can end up with classes that
4613 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004614 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004615 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004616 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004617 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004618 // Compile time verification failed with a soft error. Compile time verification can fail
4619 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004620 // class ... {
4621 // Foo x;
4622 // .... () {
4623 // if (...) {
4624 // v1 gets assigned a type of resolved class Foo
4625 // } else {
4626 // v1 gets assigned a type of unresolved class Bar
4627 // }
4628 // iput x = v1
4629 // } }
4630 // when we merge v1 following the if-the-else it results in Conflict
4631 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4632 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4633 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4634 // at compile time).
4635 return false;
4636 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004637 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004638 // Compile time verification failed with a hard error. This is caused by invalid instructions
4639 // in the class. These errors are unrecoverable.
4640 return false;
4641 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004642 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004643 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4644 // not loading the class.
4645 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4646 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004647 return false;
4648 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004649 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004650 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004651 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004652 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004653 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004654}
4655
Alex Light5a559862016-01-29 12:24:48 -08004656void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004657 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004658 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004659 }
4660}
4661
Alex Light5a559862016-01-29 12:24:48 -08004662void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004663 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004664 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004665 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004666 return; // native or abstract method
4667 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004668 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004669 return; // nothing to process
4670 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004671 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004672 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004673 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4674 CatchHandlerIterator iterator(handlers_ptr);
4675 for (; iterator.HasNext(); iterator.Next()) {
4676 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4677 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004678 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004679 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004680 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004681 DCHECK(Thread::Current()->IsExceptionPending());
4682 Thread::Current()->ClearException();
4683 }
4684 }
4685 }
4686 handlers_ptr = iterator.EndDataPointer();
4687 }
4688}
4689
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004690ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4691 jstring name,
4692 jobjectArray interfaces,
4693 jobject loader,
4694 jobjectArray methods,
4695 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004696 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004697
4698 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4699 // code to be executed. We put it up here so we can avoid all the allocations associated with
4700 // creating the class. This can happen with (eg) jit-threads.
4701 if (!self->CanLoadClasses()) {
4702 // Make sure we don't try to load anything, potentially causing an infinite loop.
4703 ObjPtr<mirror::Throwable> pre_allocated =
4704 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4705 self->SetException(pre_allocated);
4706 return nullptr;
4707 }
4708
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004709 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004710 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004711 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004712 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004713 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004714 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004715 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004716 DCHECK(temp_klass->GetClass() != nullptr);
4717 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004718 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4719 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004720 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4721 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4722 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4723 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004724 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004725 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004726 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004727 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004728 std::string descriptor(GetDescriptorForProxy(temp_klass.Get()));
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004729 const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004730
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004731 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004732 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004733
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004734 // Insert the class before loading the fields as the field roots
4735 // (ArtField::declaring_class_) are only visited from the class
4736 // table. There can't be any suspend points between inserting the
4737 // class and setting the field arrays below.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004738 ObjPtr<mirror::Class> existing = InsertClass(descriptor.c_str(), temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004739 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004740
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004741 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004742 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004743 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004744 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004745
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004746 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4747 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004748 ArtField& interfaces_sfield = sfields->At(0);
4749 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004750 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004751 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004752
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004753 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004754 ArtField& throws_sfield = sfields->At(1);
4755 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004756 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004757 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004758
Ian Rogers466bb252011-10-14 03:29:56 -07004759 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004760 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004761
Alex Lighte64300b2015-12-15 15:02:47 -08004762 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004763 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004764 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004765 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004766 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004767
4768 // Create the methods array.
4769 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4770 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004771 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4772 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004773 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004774 self->AssertPendingOOMException();
4775 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004776 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004777 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004778
4779 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004780 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004781
4782 // Create virtual method using specified prototypes.
4783 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004784 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004785 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004786 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004787 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004788 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4789 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004790 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004791
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004792 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004793 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004794 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004795 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004796 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004797
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004798 // At this point the class is loaded. Publish a ClassLoad event.
4799 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4800 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4801
4802 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004803 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004804 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004805 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004806 // Link the fields and virtual methods, creating vtable and iftables.
4807 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004808 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004809 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004810 if (!LinkClass(self, descriptor.c_str(), temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004811 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004812 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004813 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004814 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004815 CHECK(temp_klass->IsRetired());
4816 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004817
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004818 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004819 interfaces_sfield.SetObject<false>(
4820 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004821 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004822 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4823 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004824 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004825 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004826
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004827 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4828
Vladimir Marko305c38b2018-02-14 11:50:07 +00004829 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4830 // See also ClassLinker::EnsureInitialized().
4831 if (kBitstringSubtypeCheckEnabled) {
4832 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4833 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4834 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4835 }
4836
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004837 {
4838 // Lock on klass is released. Lock new class object.
4839 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004840 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004841 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004842 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004843
4844 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004845 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004846 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004847 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4848
Ian Rogersc2b44472011-12-14 21:17:17 -08004849 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004850 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4851 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004852 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004853 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004854
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004855 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004856 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004857 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004858 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004859 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004860
4861 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004862 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004863 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004864
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004865 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004866 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004867 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004868 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08004869 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004870 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04004871}
4872
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004873std::string ClassLinker::GetDescriptorForProxy(ObjPtr<mirror::Class> proxy_class) {
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00004874 DCHECK(proxy_class->IsProxyClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004875 ObjPtr<mirror::String> name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004876 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004877 return DotToDescriptor(name->ToModifiedUtf8().c_str());
4878}
4879
Mathieu Chartiere401d142015-04-22 13:56:20 -07004880void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4881 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004882 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
4883 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01004884
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004885 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
4886 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07004887 ArtMethod* proxy_constructor =
4888 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08004889 DCHECK(proxy_constructor != nullptr)
4890 << "Could not find <init> method in java.lang.reflect.Proxy";
4891
Jeff Haodb8a6642014-08-14 17:18:52 -07004892 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4893 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07004894 DCHECK(out != nullptr);
4895 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01004896 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004897 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01004898 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004899 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
4900 kAccPublic |
4901 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004902 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004903
4904 // Set the original constructor method.
4905 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08004906}
4907
Mathieu Chartiere401d142015-04-22 13:56:20 -07004908void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004909 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07004910 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4911 CHECK_STREQ(np->GetName(), "<init>");
4912 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004913 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004914}
4915
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004916void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004917 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004918 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004919 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07004920 DCHECK(out != nullptr);
4921 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07004922
Alex Lighte9dd04f2016-03-16 16:09:45 -07004923 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004924 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07004925 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4926 // preference to the invocation handler.
4927 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4928 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07004929 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
4930 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07004931 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4932
4933 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4934 // method they copy might (if it's a default method).
4935 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04004936
Vladimir Markod1ee20f2017-08-17 09:21:16 +00004937 // Set the original interface method.
4938 out->SetDataPtrSize(prototype, image_pointer_size_);
4939
Ian Rogers466bb252011-10-14 03:29:56 -07004940 // At runtime the method looks like a reference and argument saving method, clone the code
4941 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004942 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08004943}
Jesse Wilson95caa792011-10-12 18:14:17 -04004944
Mathieu Chartiere401d142015-04-22 13:56:20 -07004945void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07004946 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004947 CHECK(!prototype->IsFinal());
4948 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07004949 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08004950
4951 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4952 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08004953 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01004954 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04004955}
4956
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004957bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07004958 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004959 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004960 return true;
4961 }
4962 if (!can_init_statics) {
4963 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004964 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004965 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004966 return false;
4967 }
4968 // Check if there are encoded static values needing initialization.
4969 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08004970 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004971 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004972 if (dex_class_def->static_values_off_ != 0) {
4973 return false;
4974 }
4975 }
Alex Lighteb7c1442015-08-31 13:17:42 -07004976 // If we are a class we need to initialize all interfaces with default methods when we are
4977 // initialized. Check all of them.
4978 if (!klass->IsInterface()) {
4979 size_t num_interfaces = klass->GetIfTableCount();
4980 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004981 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07004982 if (iface->HasDefaultMethods() &&
4983 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
4984 return false;
4985 }
4986 }
4987 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004988 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07004989 if (klass->IsInterface() || !klass->HasSuperClass()) {
4990 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004991 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004992 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07004993 if (!can_init_parents && !super_class->IsInitialized()) {
4994 return false;
4995 }
4996 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004997}
4998
Igor Murashkinb1d8c312015-08-04 11:18:43 -07004999bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
5000 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005001 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5002
5003 // Are we already initialized and therefore done?
5004 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5005 // an initialized class will never change its state.
5006 if (klass->IsInitialized()) {
5007 return true;
5008 }
5009
5010 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005011 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005012 return false;
5013 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005014
Ian Rogers7b078e82014-09-10 14:44:24 -07005015 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005016 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005017 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005018 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005019
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005020 // Re-check under the lock in case another thread initialized ahead of us.
5021 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005022 return true;
5023 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005024
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005025 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005026 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005027 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005028 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005029 return false;
5030 }
5031
Vladimir Marko72ab6842017-01-20 19:32:50 +00005032 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5033 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005034
5035 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005036 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005037 if (!klass->IsVerified()) {
5038 // We failed to verify, expect either the klass to be erroneous or verification failed at
5039 // compile time.
5040 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005041 // The class is erroneous. This may be a verifier error, or another thread attempted
5042 // verification and/or initialization and failed. We can distinguish those cases by
5043 // whether an exception is already pending.
5044 if (self->IsExceptionPending()) {
5045 // Check that it's a VerifyError.
5046 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005047 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005048 } else {
5049 // Check that another thread attempted initialization.
5050 DCHECK_NE(0, klass->GetClinitThreadId());
5051 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5052 // Need to rethrow the previous failure now.
5053 ThrowEarlierClassFailure(klass.Get(), true);
5054 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005055 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005056 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005057 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005058 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
Vladimir Markod79b37b2018-11-02 13:06:22 +00005059 self->AssertNoPendingException();
5060 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005061 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005062 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005063 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005064 } else {
5065 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005066 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005067
5068 // A separate thread could have moved us all the way to initialized. A "simple" example
5069 // involves a subclass of the current class being initialized at the same time (which
5070 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005071 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005072 if (klass->IsInitialized()) {
5073 return true;
5074 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005075 }
5076
Vladimir Marko2c64a832018-01-04 11:31:56 +00005077 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005078 // initializing higher up the stack or another thread has beat us
5079 // to initializing and we need to wait. Either way, this
5080 // invocation of InitializeClass will not be responsible for
5081 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005082 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005083 // Could have got an exception during verification.
5084 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005085 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005086 return false;
5087 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005088 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005089 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005090 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005091 return true;
5092 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005093 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005094 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005095 }
5096
Jeff Haoe2e40342017-07-19 10:45:18 -07005097 // Try to get the oat class's status for this class if the oat file is present. The compiler
5098 // tries to validate superclass descriptors, and writes the result into the oat file.
5099 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5100 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5101 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005102 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005103 const Runtime* runtime = Runtime::Current();
5104 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5105 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5106 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005107 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005108 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005109 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005110 return false;
5111 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005112 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005113
Vladimir Marko2c64a832018-01-04 11:31:56 +00005114 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005115 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005116
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005117 // From here out other threads may observe that we're initializing and so changes of state
5118 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005119 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005120 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005121
5122 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005123 }
5124
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005125 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005126 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005127 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005128 if (!super_class->IsInitialized()) {
5129 CHECK(!super_class->IsInterface());
5130 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005131 StackHandleScope<1> hs(self);
5132 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07005133 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005134 if (!super_initialized) {
5135 // The super class was verified ahead of entering initializing, we should only be here if
5136 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005137 // For the case of aot compiler, the super class might also be initializing but we don't
5138 // want to process circular dependencies in pre-compile.
5139 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005140 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005141 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005142 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005143 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005144 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005145 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005146 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005147 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005148 return false;
5149 }
Ian Rogers1bddec32012-02-04 12:27:34 -08005150 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005151 }
5152
Alex Lighteb7c1442015-08-31 13:17:42 -07005153 if (!klass->IsInterface()) {
5154 // Initialize interfaces with default methods for the JLS.
5155 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005156 // Only setup the (expensive) handle scope if we actually need to.
5157 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005158 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005159 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5160 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005161 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005162 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005163 CHECK(handle_scope_iface->IsInterface());
5164 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5165 // We have already done this for this interface. Skip it.
5166 continue;
5167 }
5168 // We cannot just call initialize class directly because we need to ensure that ALL
5169 // interfaces with default methods are initialized. Non-default interface initialization
5170 // will not affect other non-default super-interfaces.
5171 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5172 handle_scope_iface,
5173 can_init_statics,
5174 can_init_parents);
5175 if (!iface_initialized) {
5176 ObjectLock<mirror::Class> lock(self, klass);
5177 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005178 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005179 return false;
5180 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005181 }
5182 }
5183 }
5184
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005185 const size_t num_static_fields = klass->NumStaticFields();
5186 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005187 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005188 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005189 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005190 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005191 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005192
5193 // Eagerly fill in static fields so that the we don't have to do as many expensive
5194 // Class::FindStaticField in ResolveField.
5195 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005196 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005197 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005198 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005199 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005200 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005201 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5202 field,
5203 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5204 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005205 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005206 } else {
5207 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005208 }
5209 }
5210
Vladimir Markoe11dd502017-12-08 14:09:45 +00005211 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5212 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005213 this,
5214 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005215 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005216
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005217 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005218 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005219 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005220 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5221 if (!value_it.HasNext()) {
5222 break;
5223 }
5224 ArtField* art_field = ResolveField(field.GetIndex(),
5225 dex_cache,
5226 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005227 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005228 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005229 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005230 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005231 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005232 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005233 if (self->IsExceptionPending()) {
5234 break;
5235 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005236 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005237 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005238 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005239 }
5240 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005241
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005242
Mathieu Chartierda595be2016-08-10 13:57:39 -07005243 if (!self->IsExceptionPending()) {
5244 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5245 if (clinit != nullptr) {
5246 CHECK(can_init_statics);
5247 JValue result;
5248 clinit->Invoke(self, nullptr, 0, &result, "V");
5249 }
5250 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005251 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005252 uint64_t t1 = NanoTime();
5253
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005254 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005255 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005256 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005257
5258 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005259 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005260 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005261 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005262 } else if (Runtime::Current()->IsTransactionAborted()) {
5263 // The exception thrown when the transaction aborted has been caught and cleared
5264 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005265 VLOG(compiler) << "Return from class initializer of "
5266 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005267 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02005268 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005269 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005270 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005271 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005272 RuntimeStats* global_stats = Runtime::Current()->GetStats();
5273 RuntimeStats* thread_stats = self->GetStats();
5274 ++global_stats->class_init_count;
5275 ++thread_stats->class_init_count;
5276 global_stats->class_init_time_ns += (t1 - t0);
5277 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005278 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005279 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005280 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005281 std::string temp;
5282 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005283 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005284 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08005285 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005286 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005287 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005288 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005289 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005290}
5291
Alex Lighteb7c1442015-08-31 13:17:42 -07005292// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5293// and perform the initialization only on those interfaces that contain default methods.
5294bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5295 Handle<mirror::Class> iface,
5296 bool can_init_statics,
5297 bool can_init_parents) {
5298 CHECK(iface->IsInterface());
5299 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005300 // Only create the (expensive) handle scope if we need it.
5301 if (UNLIKELY(num_direct_ifaces > 0)) {
5302 StackHandleScope<1> hs(self);
5303 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5304 // First we initialize all of iface's super-interfaces recursively.
5305 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005306 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005307 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005308 if (!super_iface->HasBeenRecursivelyInitialized()) {
5309 // Recursive step
5310 handle_super_iface.Assign(super_iface);
5311 if (!InitializeDefaultInterfaceRecursive(self,
5312 handle_super_iface,
5313 can_init_statics,
5314 can_init_parents)) {
5315 return false;
5316 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005317 }
5318 }
5319 }
5320
5321 bool result = true;
5322 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5323 // initialize if we don't have default methods.
5324 if (iface->HasDefaultMethods()) {
5325 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5326 }
5327
5328 // Mark that this interface has undergone recursive default interface initialization so we know we
5329 // can skip it on any later class initializations. We do this even if we are not a default
5330 // interface since we can still avoid the traversal. This is purely a performance optimization.
5331 if (result) {
5332 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005333 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5334 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5335 // initialization is a performance optimization (to avoid another idempotent visit
5336 // for other implementing classes/interfaces), and can be revisited later.
5337 ObjectTryLock<mirror::Class> lock(self, iface);
5338 if (lock.Acquired()) {
5339 iface->SetRecursivelyInitialized();
5340 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005341 }
5342 return result;
5343}
5344
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005345bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5346 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005347 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005348 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005349 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005350 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005351 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005352 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005353
5354 // When we wake up, repeat the test for init-in-progress. If
5355 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005356 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005357 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005358 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005359 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005360 return false;
5361 }
5362 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005363 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005364 continue;
5365 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005366 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005367 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005368 // Compile time initialization failed.
5369 return false;
5370 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005371 if (klass->IsErroneous()) {
5372 // The caller wants an exception, but it was thrown in a
5373 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005374 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005375 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005376 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005377 return false;
5378 }
5379 if (klass->IsInitialized()) {
5380 return true;
5381 }
David Sehr709b0702016-10-13 09:12:37 -07005382 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005383 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005384 }
Ian Rogers07140832014-09-30 15:43:59 -07005385 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005386}
5387
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005388static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5389 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005390 ArtMethod* method,
5391 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005392 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005393 DCHECK(Thread::Current()->IsExceptionPending());
5394 DCHECK(!m->IsProxyMethod());
5395 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005396 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5397 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005398 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005399 std::string return_type = dex_file->PrettyType(return_type_idx);
5400 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005401 ThrowWrappedLinkageError(klass.Get(),
5402 "While checking class %s method %s signature against %s %s: "
5403 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005404 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5405 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005406 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005407 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005408 return_type.c_str(), class_loader.c_str());
5409}
5410
5411static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5412 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005413 ArtMethod* method,
5414 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005415 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005416 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005417 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005418 DCHECK(Thread::Current()->IsExceptionPending());
5419 DCHECK(!m->IsProxyMethod());
5420 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005421 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5422 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005423 ThrowWrappedLinkageError(klass.Get(),
5424 "While checking class %s method %s signature against %s %s: "
5425 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005426 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5427 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005428 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005429 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005430 index, arg_type.c_str(), class_loader.c_str());
5431}
5432
5433static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5434 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005435 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005436 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005437 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005438 ThrowLinkageError(klass.Get(),
5439 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005440 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5441 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005442 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005443 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005444 error_msg.c_str());
5445}
5446
Ian Rogersb5fb2072014-12-02 17:22:02 -08005447static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005448 Handle<mirror::Class> klass,
5449 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005450 ArtMethod* method1,
5451 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005452 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005453 {
5454 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005455 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005456 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005457 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005458 return false;
5459 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005460 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005461 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005462 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005463 return false;
5464 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005465 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005466 ThrowSignatureMismatch(klass, super_klass, method1,
5467 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005468 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005469 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005470 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005471 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005472 return false;
5473 }
5474 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005475 const dex::TypeList* types1 = method1->GetParameterTypeList();
5476 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005477 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005478 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005479 ThrowSignatureMismatch(klass, super_klass, method1,
5480 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005481 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005482 return false;
5483 }
5484 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005485 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005486 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005487 ThrowSignatureMismatch(klass, super_klass, method1,
5488 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005489 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005490 return false;
5491 }
5492 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005493 }
5494 uint32_t num_types = types1->Size();
5495 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005496 ThrowSignatureMismatch(klass, super_klass, method1,
5497 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005498 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005499 return false;
5500 }
5501 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005502 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005503 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005504 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005505 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005506 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005507 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005508 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005509 return false;
5510 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005511 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005512 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005513 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005514 if (UNLIKELY(other_param_type == nullptr)) {
5515 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005516 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005517 return false;
5518 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005519 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005520 ThrowSignatureMismatch(klass, super_klass, method1,
5521 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5522 i,
David Sehr709b0702016-10-13 09:12:37 -07005523 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005524 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005525 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005526 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005527 return false;
5528 }
5529 }
5530 return true;
5531}
5532
5533
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005534bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005535 if (klass->IsInterface()) {
5536 return true;
5537 }
Ian Rogers151f2212014-05-06 11:27:27 -07005538 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005539 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005540 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005541 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005542 if (klass->HasSuperClass() &&
5543 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005544 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005545 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005546 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5547 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5548 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005549 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5550 klass,
5551 super_klass,
5552 m,
5553 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005554 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005555 return false;
5556 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005557 }
5558 }
5559 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005560 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005561 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5562 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5563 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005564 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005565 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5566 j, image_pointer_size_);
5567 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5568 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005569 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5570 klass,
5571 super_klass,
5572 m,
5573 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005574 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005575 return false;
5576 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005577 }
5578 }
5579 }
5580 }
5581 return true;
5582}
5583
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005584bool ClassLinker::EnsureInitialized(Thread* self,
5585 Handle<mirror::Class> c,
5586 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005587 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005588 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005589
Mathieu Chartier524507a2014-08-27 15:28:28 -07005590 if (c->IsInitialized()) {
Andreas Gampe5b20b352018-10-11 19:03:20 -07005591 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005592 return true;
5593 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005594 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5595 //
5596 // Ensure the bitstring is initialized before any of the class initialization
5597 // logic occurs. Once a class initializer starts running, objects can
5598 // escape into the heap and use the subtype checking code.
5599 //
5600 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5601 // can be used as a source for the IsSubClass check, and that all ancestors
5602 // of the class are Assigned (can be used as a target for IsSubClass check)
5603 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005604 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005605 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005606 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005607 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5608 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005609 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005610 if (!success) {
5611 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005612 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005613 }
5614 } else {
5615 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005616 }
5617 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005618}
5619
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005620void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5621 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005622 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005623 for (ArtField& field : new_class->GetIFields()) {
5624 if (field.GetDeclaringClass() == temp_class) {
5625 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005626 }
5627 }
5628
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005629 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005630 for (ArtField& field : new_class->GetSFields()) {
5631 if (field.GetDeclaringClass() == temp_class) {
5632 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005633 }
5634 }
5635
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005636 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005637 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005638 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005639 if (method.GetDeclaringClass() == temp_class) {
5640 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005641 }
5642 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005643
5644 // Make sure the remembered set and mod-union tables know that we updated some of the native
5645 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005646 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005647}
5648
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005649void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005650 CHECK(class_loader->GetAllocator() == nullptr);
5651 CHECK(class_loader->GetClassTable() == nullptr);
5652 Thread* const self = Thread::Current();
5653 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005654 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005655 // Create and set the class table.
5656 data.class_table = new ClassTable;
5657 class_loader->SetClassTable(data.class_table);
5658 // Create and set the linear allocator.
5659 data.allocator = Runtime::Current()->CreateLinearAlloc();
5660 class_loader->SetAllocator(data.allocator);
5661 // Add to the list so that we know to free the data later.
5662 class_loaders_.push_back(data);
5663}
5664
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005665ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005666 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005667 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005668 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005669 ClassTable* class_table = class_loader->GetClassTable();
5670 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005671 RegisterClassLoader(class_loader);
5672 class_table = class_loader->GetClassTable();
5673 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005674 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005675 return class_table;
5676}
5677
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005678ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005679 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005680}
5681
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005682static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005683 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005684 while (klass->HasSuperClass()) {
5685 klass = klass->GetSuperClass();
5686 if (klass->ShouldHaveImt()) {
5687 return klass->GetImt(pointer_size);
5688 }
5689 }
5690 return nullptr;
5691}
5692
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005693bool ClassLinker::LinkClass(Thread* self,
5694 const char* descriptor,
5695 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005696 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005697 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005698 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005699
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005700 if (!LinkSuperClass(klass)) {
5701 return false;
5702 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005703 ArtMethod* imt_data[ImTable::kSize];
5704 // If there are any new conflicts compared to super class.
5705 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005706 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005707 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005708 return false;
5709 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005710 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005711 return false;
5712 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005713 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005714 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005715 return false;
5716 }
5717 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005718 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005719
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005720 ImTable* imt = nullptr;
5721 if (klass->ShouldHaveImt()) {
5722 // If there are any new conflicts compared to the super class we can not make a copy. There
5723 // can be cases where both will have a conflict method at the same slot without having the same
5724 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5725 // will possibly create a table that is incorrect for either of the classes.
5726 // Same IMT with new_conflict does not happen very often.
5727 if (!new_conflict) {
5728 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5729 if (super_imt != nullptr) {
5730 bool imt_equals = true;
5731 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5732 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5733 }
5734 if (imt_equals) {
5735 imt = super_imt;
5736 }
5737 }
5738 }
5739 if (imt == nullptr) {
5740 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5741 imt = reinterpret_cast<ImTable*>(
5742 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5743 if (imt == nullptr) {
5744 return false;
5745 }
5746 imt->Populate(imt_data, image_pointer_size_);
5747 }
5748 }
5749
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005750 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5751 // We don't need to retire this class as it has no embedded tables or it was created the
5752 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005753 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005754
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005755 if (klass->ShouldHaveEmbeddedVTable()) {
5756 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005757 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005758 if (klass->ShouldHaveImt()) {
5759 klass->SetImt(imt, image_pointer_size_);
5760 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005761
5762 // Update CHA info based on whether we override methods.
5763 // Have to do this before setting the class as resolved which allows
5764 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005765 if (cha_ != nullptr) {
5766 cha_->UpdateAfterLoadingOf(klass);
5767 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005768
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005769 // This will notify waiters on klass that saw the not yet resolved
5770 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005771 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005772 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005773 } else {
5774 CHECK(!klass->IsResolved());
5775 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005776 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005777 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005778 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5779 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5780 // may not see any references to the target space and clean the card for a class if another
5781 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005782 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005783 klass->SetSFieldsPtrUnchecked(nullptr);
5784 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005785 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005786 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005787 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005788 return false;
5789 }
5790
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005791 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5792 ObjectLock<mirror::Class> lock(self, h_new_class);
5793 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005794
5795 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005796 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005797 ObjPtr<mirror::ClassLoader> const class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005798 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005799 ObjPtr<mirror::Class> existing = table->UpdateClass(descriptor, h_new_class.Get(),
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005800 ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005801 if (class_loader != nullptr) {
5802 // We updated the class in the class table, perform the write barrier so that the GC knows
5803 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005804 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005805 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005806 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005807 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005808 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5809 }
5810 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005811
Mingyao Yang063fc772016-08-02 11:02:54 -07005812 // Update CHA info based on whether we override methods.
5813 // Have to do this before setting the class as resolved which allows
5814 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005815 if (cha_ != nullptr) {
5816 cha_->UpdateAfterLoadingOf(h_new_class);
5817 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005818
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005819 // This will notify waiters on temp class that saw the not yet resolved class in the
5820 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005821 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005822
Vladimir Marko2c64a832018-01-04 11:31:56 +00005823 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005824 // This will notify waiters on new_class that saw the not yet resolved
5825 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005826 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005827 // Return the new class.
5828 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005829 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005830 return true;
5831}
5832
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005833bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005834 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005835 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005836 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5837 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005838 // Check that a class does not inherit from itself directly.
5839 //
5840 // TODO: This is a cheap check to detect the straightforward case
5841 // of a class extending itself (b/28685551), but we should do a
5842 // proper cycle detection on loaded classes, to detect all cases
5843 // of class circularity errors (b/28830038).
5844 if (super_class_idx == class_def.class_idx_) {
5845 ThrowClassCircularityError(klass.Get(),
5846 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005847 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005848 return false;
5849 }
5850
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005851 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005852 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005853 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005854 return false;
5855 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005856 // Verify
5857 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005858 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005859 super_class->PrettyDescriptor().c_str(),
5860 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005861 return false;
5862 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005863 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005864 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005865 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005866 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005867 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005868 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005869 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005870 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005871 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005872 DCHECK(Thread::Current()->IsExceptionPending());
5873 return false;
5874 }
5875 // Verify
5876 if (!klass->CanAccess(interface)) {
5877 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005878 ThrowIllegalAccessError(klass.Get(),
5879 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005880 interface->PrettyDescriptor().c_str(),
5881 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005882 return false;
5883 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005884 }
5885 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07005886 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005887 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005888 return true;
5889}
5890
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005891bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005892 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005893 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005894 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
5895 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005896 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005897 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005898 return false;
5899 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005900 return true;
5901 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005902 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005903 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07005904 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005905 return false;
5906 }
5907 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005908 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00005909 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
5910 return false;
5911 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01005912 if (super->IsFinal()) {
5913 ThrowVerifyError(klass.Get(),
5914 "Superclass %s of %s is declared final",
5915 super->PrettyDescriptor().c_str(),
5916 klass->PrettyDescriptor().c_str());
5917 return false;
5918 }
5919 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005920 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005921 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07005922 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01005923 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005924 return false;
5925 }
5926 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005927 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07005928 super->PrettyDescriptor().c_str(),
5929 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005930 return false;
5931 }
Elliott Hughes20cde902011-10-04 17:37:27 -07005932
Brian Carlstromf3632832014-05-20 15:36:53 -07005933 // Inherit kAccClassIsFinalizable from the superclass in case this
5934 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07005935 if (super->IsFinalizable()) {
5936 klass->SetFinalizable();
5937 }
5938
Mathieu Chartiere4275c02015-08-06 15:34:15 -07005939 // Inherit class loader flag form super class.
5940 if (super->IsClassLoaderClass()) {
5941 klass->SetClassLoaderClass();
5942 }
5943
Elliott Hughes2da50362011-10-10 16:57:08 -07005944 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005945 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07005946 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07005947 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07005948 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07005949 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005950 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005951 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005952 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08005953 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07005954 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07005955 return false;
5956 }
Elliott Hughes2da50362011-10-10 16:57:08 -07005957
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005958 if (kIsDebugBuild) {
5959 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005960 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005961 CHECK(super->IsResolved());
5962 super = super->GetSuperClass();
5963 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005964 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005965 return true;
5966}
5967
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005968// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005969bool ClassLinker::LinkMethods(Thread* self,
5970 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005971 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005972 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005973 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005974 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07005975 // A map from vtable indexes to the method they need to be updated to point to. Used because we
5976 // need to have default methods be in the virtuals array of each class but we don't set that up
5977 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07005978 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07005979 // Link virtual methods then interface methods.
5980 // We set up the interface lookup table first because we need it to determine if we need to update
5981 // any vtable entries with new default method implementations.
5982 return SetupInterfaceLookupTable(self, klass, interfaces)
5983 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005984 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005985}
5986
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005987// Comparator for name and signature of a method, used in finding overriding methods. Implementation
5988// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
5989// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01005990class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005991 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07005992 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005993 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005994 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
5995 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07005996 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005997 }
5998
5999 const char* GetName() {
6000 if (name_ == nullptr) {
6001 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6002 }
6003 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006004 }
6005
Mathieu Chartiere401d142015-04-22 13:56:20 -07006006 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006007 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006008 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006009 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006010 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006011 if (dex_file_ == other_dex_file) {
6012 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6013 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006014 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006015 uint32_t other_name_len;
6016 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6017 &other_name_len);
6018 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6019 return false;
6020 }
6021 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6022 }
6023
6024 private:
6025 // Dex file for the method to compare against.
6026 const DexFile* const dex_file_;
6027 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006028 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006029 // Lazily computed name from the dex file's strings.
6030 const char* name_;
6031 // Lazily computed name length.
6032 uint32_t name_len_;
6033};
6034
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006035class LinkVirtualHashTable {
6036 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006037 LinkVirtualHashTable(Handle<mirror::Class> klass,
6038 size_t hash_size,
6039 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006040 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006041 : klass_(klass),
6042 hash_size_(hash_size),
6043 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006044 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006045 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6046 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006047
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006048 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006049 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6050 virtual_method_index, image_pointer_size_);
6051 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006052 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006053 uint32_t index = hash % hash_size_;
6054 // Linear probe until we have an empty slot.
6055 while (hash_table_[index] != invalid_index_) {
6056 if (++index == hash_size_) {
6057 index = 0;
6058 }
6059 }
6060 hash_table_[index] = virtual_method_index;
6061 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006062
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006063 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006064 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006065 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006066 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006067 size_t index = hash % hash_size_;
6068 while (true) {
6069 const uint32_t value = hash_table_[index];
6070 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6071 // the block and can safely assume not found.
6072 if (value == invalid_index_) {
6073 break;
6074 }
6075 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006076 ArtMethod* virtual_method =
6077 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6078 if (comparator->HasSameNameAndSignature(
6079 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006080 hash_table_[index] = removed_index_;
6081 return value;
6082 }
6083 }
6084 if (++index == hash_size_) {
6085 index = 0;
6086 }
6087 }
6088 return GetNotFoundIndex();
6089 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006090
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006091 static uint32_t GetNotFoundIndex() {
6092 return invalid_index_;
6093 }
6094
6095 private:
6096 static const uint32_t invalid_index_;
6097 static const uint32_t removed_index_;
6098
6099 Handle<mirror::Class> klass_;
6100 const size_t hash_size_;
6101 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006102 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006103};
6104
6105const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6106const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6107
Stephen Hines1ddd9132017-02-08 01:51:18 -08006108bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006109 Thread* self,
6110 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006111 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006112 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006113 if (klass->IsInterface()) {
6114 // No vtable.
6115 if (!IsUint<16>(num_virtual_methods)) {
6116 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6117 return false;
6118 }
6119 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006120 // Assign each method an IMT index and set the default flag.
6121 for (size_t i = 0; i < num_virtual_methods; ++i) {
6122 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6123 m->SetMethodIndex(i);
6124 if (!m->IsAbstract()) {
6125 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6126 has_defaults = true;
6127 }
6128 }
6129 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6130 // during initialization. This is a performance optimization. We could simply traverse the
6131 // virtual_methods_ array again during initialization.
6132 if (has_defaults) {
6133 klass->SetHasDefaultMethods();
6134 }
6135 return true;
6136 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006137 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6138 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006139 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006140 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006141 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006142 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006143 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006144 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006145 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006146 return false;
6147 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006148 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006149 vtable->SetElementPtrSize(
6150 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006151 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006152 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6153 // might give us new default methods). If no new interfaces then we can skip the rest since
6154 // the class cannot override any of the super-class's methods. This is required for
6155 // correctness since without it we might not update overridden default method vtable entries
6156 // correctly.
6157 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006158 klass->SetVTable(vtable.Get());
6159 return true;
6160 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006161 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006162 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07006163 auto* super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07006164 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006165 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6166 // might give us new default methods). See comment above.
6167 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006168 klass->SetVTable(super_vtable);
6169 return true;
6170 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006171 vtable = hs.NewHandle(
6172 ObjPtr<mirror::PointerArray>::DownCast(super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006173 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006174 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006175 return false;
6176 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006177 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006178 // How the algorithm works:
6179 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6180 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6181 // method which has not been matched to a vtable method, and j if the virtual method at the
6182 // index overrode the super virtual method at index j.
6183 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6184 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6185 // the need for the initial vtable which we later shrink back down).
6186 // 3. Add non overridden methods to the end of the vtable.
6187 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006188 // + 1 so that even if we only have new default methods we will still be able to use this hash
6189 // table (i.e. it will never have 0 size).
6190 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006191 uint32_t* hash_table_ptr;
6192 std::unique_ptr<uint32_t[]> hash_heap_storage;
6193 if (hash_table_size <= kMaxStackHash) {
6194 hash_table_ptr = reinterpret_cast<uint32_t*>(
6195 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6196 } else {
6197 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6198 hash_table_ptr = hash_heap_storage.get();
6199 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006200 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006201 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006202 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006203 DCHECK(klass->GetVirtualMethodDuringLinking(
6204 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006205 hash_table.Add(i);
6206 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006207 // Loop through each super vtable method and see if they are overridden by a method we added to
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006208 // the hash table.
6209 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006210 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006211 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006212 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6213 super_method->GetAccessFlags())) {
6214 // Continue on to the next method since this one is package private and canot be overridden.
6215 // Before Android 4.1, the package-private method super_method might have been incorrectly
6216 // overridden.
6217 continue;
6218 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006219 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006220 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006221 // We remove the method so that subsequent lookups will be faster by making the hash-map
6222 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006223 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6224 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006225 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6226 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006227 if (super_method->IsFinal()) {
6228 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6229 virtual_method->PrettyMethod().c_str(),
6230 super_method->GetDeclaringClassDescriptor());
6231 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006232 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006233 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6234 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006235 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006236 // We didn't directly override this method but we might through default methods...
6237 // Check for default method update.
6238 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006239 switch (FindDefaultMethodImplementation(self,
6240 super_method,
6241 klass,
6242 /*out*/&default_method)) {
6243 case DefaultMethodSearchResult::kDefaultConflict: {
6244 // A conflict was found looking for default methods. Note this (assuming it wasn't
6245 // pre-existing) in the translations map.
6246 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6247 // Don't generate another conflict method to reduce memory use as an optimization.
6248 default_translations->insert(
6249 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6250 }
6251 break;
6252 }
6253 case DefaultMethodSearchResult::kAbstractFound: {
6254 // No conflict but method is abstract.
6255 // We note that this vtable entry must be made abstract.
6256 if (UNLIKELY(!super_method->IsAbstract())) {
6257 default_translations->insert(
6258 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6259 }
6260 break;
6261 }
6262 case DefaultMethodSearchResult::kDefaultFound: {
6263 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6264 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6265 // Found a default method implementation that is new.
6266 // TODO Refactor this add default methods to virtuals here and not in
6267 // LinkInterfaceMethods maybe.
6268 // The problem is default methods might override previously present
6269 // default-method or miranda-method vtable entries from the superclass.
6270 // Unfortunately we need these to be entries in this class's virtuals. We do not
6271 // give these entries there until LinkInterfaceMethods so we pass this map around
6272 // to let it know which vtable entries need to be updated.
6273 // Make a note that vtable entry j must be updated, store what it needs to be updated
6274 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6275 // then.
6276 default_translations->insert(
6277 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006278 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6279 << " overridden by default "
6280 << default_method->PrettyMethod()
6281 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006282 }
6283 break;
6284 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006285 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006286 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006287 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006288 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006289 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006290 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006291 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006292 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6293 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006294 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006295 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006296 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006297 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006298 local_method->SetMethodIndex(actual_count);
6299 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006300 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006301 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006302 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006303 return false;
6304 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006305 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006306 CHECK_LE(actual_count, max_count);
6307 if (actual_count < max_count) {
Vladimir Markobcf17522018-06-01 13:14:32 +01006308 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006309 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006310 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006311 return false;
6312 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006313 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006314 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006315 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006316 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006317 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006318 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6319 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006320 return false;
6321 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006322 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006323 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006324 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006325 return false;
6326 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006327 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006328 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6329 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006330 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006331 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006332 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006333 }
6334 return true;
6335}
6336
Alex Light9139e002015-10-09 15:59:48 -07006337// Determine if the given iface has any subinterface in the given list that declares the method
6338// specified by 'target'.
6339//
6340// Arguments
6341// - self: The thread we are running on
6342// - target: A comparator that will match any method that overrides the method we are checking for
6343// - iftable: The iftable we are searching for an overriding method on.
6344// - ifstart: The index of the interface we are checking to see if anything overrides
6345// - iface: The interface we are checking to see if anything overrides.
6346// - image_pointer_size:
6347// The image pointer size.
6348//
6349// Returns
6350// - True: There is some method that matches the target comparator defined in an interface that
6351// is a subtype of iface.
6352// - False: There is no method that matches the target comparator in any interface that is a subtype
6353// of iface.
6354static bool ContainsOverridingMethodOf(Thread* self,
6355 MethodNameAndSignatureComparator& target,
6356 Handle<mirror::IfTable> iftable,
6357 size_t ifstart,
6358 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006359 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006360 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006361 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006362 DCHECK(iface != nullptr);
6363 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006364 DCHECK_GE(ifstart, 0u);
6365 DCHECK_LT(ifstart, iftable->Count());
6366 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6367 DCHECK(iface->IsInterface());
6368
6369 size_t iftable_count = iftable->Count();
6370 StackHandleScope<1> hs(self);
6371 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6372 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6373 // Skip ifstart since our current interface obviously cannot override itself.
6374 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006375 // Iterate through every method on this interface. The order does not matter.
6376 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006377 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006378 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006379 // Check if the i'th interface is a subtype of this one.
6380 if (iface->IsAssignableFrom(current_iface.Get())) {
6381 return true;
6382 }
6383 break;
6384 }
6385 }
6386 }
6387 return false;
6388}
6389
Alex Lighteb7c1442015-08-31 13:17:42 -07006390// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006391// out_default_method and returns kDefaultFound on success. If no default method was found return
6392// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6393// default_method conflict) it will return kDefaultConflict.
6394ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6395 Thread* self,
6396 ArtMethod* target_method,
6397 Handle<mirror::Class> klass,
6398 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006399 DCHECK(self != nullptr);
6400 DCHECK(target_method != nullptr);
6401 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006402
6403 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006404
6405 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6406 // table. This lets us walk the table backwards when searching for default methods. The first one
6407 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6408 // track of it and then continue checking all other interfaces, since we need to throw an error if
6409 // we encounter conflicting default method implementations (one is not a subtype of the other).
6410 //
6411 // The order of unrelated interfaces does not matter and is not defined.
6412 size_t iftable_count = klass->GetIfTableCount();
6413 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006414 // No interfaces. We have already reset out to null so just return kAbstractFound.
6415 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006416 }
6417
Alex Light9139e002015-10-09 15:59:48 -07006418 StackHandleScope<3> hs(self);
6419 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006420 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006421 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006422 MethodNameAndSignatureComparator target_name_comparator(
6423 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6424 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006425 for (size_t k = iftable_count; k != 0; ) {
6426 --k;
6427
Alex Lighteb7c1442015-08-31 13:17:42 -07006428 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006429
6430 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006431 // Iterate through every declared method on this interface. The order does not matter.
6432 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6433 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006434 // Skip abstract methods and methods with different names.
6435 if (current_method->IsAbstract() ||
6436 !target_name_comparator.HasSameNameAndSignature(
6437 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6438 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006439 } else if (!current_method->IsPublic()) {
6440 // The verifier should have caught the non-public method for dex version 37. Just warn and
6441 // skip it since this is from before default-methods so we don't really need to care that it
6442 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006443 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6444 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006445 << "This will be a fatal error in subsequent versions of android. "
6446 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006447 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006448 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006449 // We have multiple default impls of the same method. This is a potential default conflict.
6450 // We need to check if this possibly conflicting method is either a superclass of the chosen
6451 // default implementation or is overridden by a non-default interface method. In either case
6452 // there is no conflict.
6453 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6454 !ContainsOverridingMethodOf(self,
6455 target_name_comparator,
6456 iftable,
6457 k,
6458 iface,
6459 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006460 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006461 << current_method->PrettyMethod() << " and "
6462 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6463 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006464 *out_default_method = nullptr;
6465 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006466 } else {
6467 break; // Continue checking at the next interface.
6468 }
6469 } else {
Alex Light9139e002015-10-09 15:59:48 -07006470 // chosen_iface == null
6471 if (!ContainsOverridingMethodOf(self,
6472 target_name_comparator,
6473 iftable,
6474 k,
6475 iface,
6476 image_pointer_size_)) {
6477 // Don't set this as the chosen interface if something else is overriding it (because that
6478 // other interface would be potentially chosen instead if it was default). If the other
6479 // interface was abstract then we wouldn't select this interface as chosen anyway since
6480 // the abstract method masks it.
6481 *out_default_method = current_method;
6482 chosen_iface.Assign(iface.Get());
6483 // We should now finish traversing the graph to find if we have default methods that
6484 // conflict.
6485 } else {
David Sehr709b0702016-10-13 09:12:37 -07006486 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6487 << "' was "
6488 << "skipped because it was overridden by an abstract method in a "
6489 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006490 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006491 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006492 break;
6493 }
6494 }
Alex Light9139e002015-10-09 15:59:48 -07006495 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006496 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6497 << "' selected "
6498 << "as the implementation for '" << target_method->PrettyMethod()
6499 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006500 return DefaultMethodSearchResult::kDefaultFound;
6501 } else {
6502 return DefaultMethodSearchResult::kAbstractFound;
6503 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006504}
6505
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006506ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006507 ArtMethod* conflict_method,
6508 ArtMethod* interface_method,
6509 ArtMethod* method,
6510 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006511 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006512 Runtime* const runtime = Runtime::Current();
6513 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6514 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6515
6516 // Create a new entry if the existing one is the shared conflict method.
6517 ArtMethod* new_conflict_method = new_entry
6518 ? runtime->CreateImtConflictMethod(linear_alloc)
6519 : conflict_method;
6520
6521 // Allocate a new table. Note that we will leak this table at the next conflict,
6522 // but that's a tradeoff compared to making the table fixed size.
6523 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006524 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6525 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006526 if (data == nullptr) {
6527 LOG(ERROR) << "Failed to allocate conflict table";
6528 return conflict_method;
6529 }
6530 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6531 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006532 method,
6533 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006534
6535 // Do a fence to ensure threads see the data in the table before it is assigned
6536 // to the conflict method.
6537 // Note that there is a race in the presence of multiple threads and we may leak
6538 // memory from the LinearAlloc, but that's a tradeoff compared to using
6539 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006540 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006541 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006542 return new_conflict_method;
6543}
6544
Vladimir Marko921094a2017-01-12 18:37:06 +00006545bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6546 Handle<mirror::Class> klass,
6547 Handle<mirror::IfTable> iftable) {
6548 DCHECK(!klass->IsInterface());
6549 const bool has_superclass = klass->HasSuperClass();
6550 const bool extend_super_iftable = has_superclass;
6551 const size_t ifcount = klass->GetIfTableCount();
6552 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6553 for (size_t i = 0; i < ifcount; ++i) {
6554 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6555 if (num_methods > 0) {
6556 const bool is_super = i < super_ifcount;
6557 // This is an interface implemented by a super-class. Therefore we can just copy the method
6558 // array from the superclass.
6559 const bool super_interface = is_super && extend_super_iftable;
6560 ObjPtr<mirror::PointerArray> method_array;
6561 if (super_interface) {
6562 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6563 DCHECK(if_table != nullptr);
6564 DCHECK(if_table->GetMethodArray(i) != nullptr);
6565 // If we are working on a super interface, try extending the existing method array.
Vladimir Markobcf17522018-06-01 13:14:32 +01006566 method_array = ObjPtr<mirror::PointerArray>::DownCast(MakeObjPtr(
6567 if_table->GetMethodArray(i)->Clone(self)));
Vladimir Marko921094a2017-01-12 18:37:06 +00006568 } else {
6569 method_array = AllocPointerArray(self, num_methods);
6570 }
6571 if (UNLIKELY(method_array == nullptr)) {
6572 self->AssertPendingOOMException();
6573 return false;
6574 }
6575 iftable->SetMethodArray(i, method_array);
6576 }
6577 }
6578 return true;
6579}
6580
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006581void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6582 ArtMethod* imt_conflict_method,
6583 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006584 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006585 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006586 // Place method in imt if entry is empty, place conflict otherwise.
6587 if (*imt_ref == unimplemented_method) {
6588 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006589 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006590 // If we are not a conflict and we have the same signature and name as the imt
6591 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006592 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6593 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006594 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006595 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006596 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006597 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006598 *imt_ref = current_method;
6599 } else {
Alex Light9139e002015-10-09 15:59:48 -07006600 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006601 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006602 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006603 } else {
6604 // Place the default conflict method. Note that there may be an existing conflict
6605 // method in the IMT, but it could be one tailored to the super class, with a
6606 // specific ImtConflictTable.
6607 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006608 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006609 }
6610}
6611
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006612void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006613 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6614 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006615 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006616 Runtime* const runtime = Runtime::Current();
6617 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6618 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006619 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006620 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006621 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006622 FillIMTFromIfTable(klass->GetIfTable(),
6623 unimplemented_method,
6624 conflict_method,
6625 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006626 /*create_conflict_tables=*/true,
6627 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006628 &new_conflict,
6629 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006630 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006631 if (!klass->ShouldHaveImt()) {
6632 return;
6633 }
6634 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6635 // we can just use the same pointer.
6636 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006637 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006638 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6639 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6640 bool same = true;
6641 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6642 ArtMethod* method = imt_data[i];
6643 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6644 if (method != super_method) {
6645 bool is_conflict_table = method->IsRuntimeMethod() &&
6646 method != unimplemented_method &&
6647 method != conflict_method;
6648 // Verify conflict contents.
6649 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6650 super_method != unimplemented_method &&
6651 super_method != conflict_method;
6652 if (!is_conflict_table || !super_conflict_table) {
6653 same = false;
6654 } else {
6655 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6656 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6657 same = same && table1->Equals(table2, image_pointer_size_);
6658 }
6659 }
6660 }
6661 if (same) {
6662 imt = super_imt;
6663 }
6664 }
6665 if (imt == nullptr) {
6666 imt = klass->GetImt(image_pointer_size_);
6667 DCHECK(imt != nullptr);
6668 imt->Populate(imt_data, image_pointer_size_);
6669 } else {
6670 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006671 }
6672}
6673
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006674ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6675 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006676 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006677 void* data = linear_alloc->Alloc(Thread::Current(),
6678 ImtConflictTable::ComputeSize(count,
6679 image_pointer_size));
6680 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6681}
6682
6683ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6684 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6685}
6686
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006687void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006688 ArtMethod* unimplemented_method,
6689 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006690 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006691 bool create_conflict_tables,
6692 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006693 /*out*/bool* new_conflict,
6694 /*out*/ArtMethod** imt) {
6695 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006696 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006697 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006698 const size_t num_virtuals = interface->NumVirtualMethods();
6699 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6700 // Virtual methods can be larger than the if table methods if there are default methods.
6701 DCHECK_GE(num_virtuals, method_array_count);
6702 if (kIsDebugBuild) {
6703 if (klass->IsInterface()) {
6704 DCHECK_EQ(method_array_count, 0u);
6705 } else {
6706 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6707 }
6708 }
6709 if (method_array_count == 0) {
6710 continue;
6711 }
6712 auto* method_array = if_table->GetMethodArray(i);
6713 for (size_t j = 0; j < method_array_count; ++j) {
6714 ArtMethod* implementation_method =
6715 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6716 if (ignore_copied_methods && implementation_method->IsCopied()) {
6717 continue;
6718 }
6719 DCHECK(implementation_method != nullptr);
6720 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6721 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6722 // or interface methods in the IMT here they will not create extra conflicts since we compare
6723 // names and signatures in SetIMTRef.
6724 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006725 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006726
6727 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6728 // the same implementation method, keep track of this to avoid creating a conflict table in
6729 // this case.
6730
6731 // Conflict table size for each IMT slot.
6732 ++conflict_counts[imt_index];
6733
6734 SetIMTRef(unimplemented_method,
6735 imt_conflict_method,
6736 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006737 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006738 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006739 }
6740 }
6741
6742 if (create_conflict_tables) {
6743 // Create the conflict tables.
6744 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006745 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006746 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006747 if (imt[i] == imt_conflict_method) {
6748 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6749 if (new_table != nullptr) {
6750 ArtMethod* new_conflict_method =
6751 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6752 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6753 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006754 } else {
6755 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006756 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006757 }
6758 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006759 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006760 }
6761 }
6762
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006763 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006764 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006765 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6766 // Virtual methods can be larger than the if table methods if there are default methods.
6767 if (method_array_count == 0) {
6768 continue;
6769 }
6770 auto* method_array = if_table->GetMethodArray(i);
6771 for (size_t j = 0; j < method_array_count; ++j) {
6772 ArtMethod* implementation_method =
6773 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6774 if (ignore_copied_methods && implementation_method->IsCopied()) {
6775 continue;
6776 }
6777 DCHECK(implementation_method != nullptr);
6778 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006779 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006780 if (!imt[imt_index]->IsRuntimeMethod() ||
6781 imt[imt_index] == unimplemented_method ||
6782 imt[imt_index] == imt_conflict_method) {
6783 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006784 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006785 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6786 const size_t num_entries = table->NumEntries(image_pointer_size_);
6787 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6788 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006789 }
6790 }
6791 }
6792}
6793
Alex Lighteb7c1442015-08-31 13:17:42 -07006794// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6795// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006796static bool NotSubinterfaceOfAny(
6797 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6798 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006799 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006800 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006801 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006802 for (ObjPtr<mirror::Class> c : classes) {
6803 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006804 return false;
6805 }
6806 }
6807 return true;
6808}
6809
6810// Fills in and flattens the interface inheritance hierarchy.
6811//
6812// By the end of this function all interfaces in the transitive closure of to_process are added to
6813// the iftable and every interface precedes all of its sub-interfaces in this list.
6814//
6815// all I, J: Interface | I <: J implies J precedes I
6816//
6817// (note A <: B means that A is a subtype of B)
6818//
6819// This returns the total number of items in the iftable. The iftable might be resized down after
6820// this call.
6821//
6822// We order this backwards so that we do not need to reorder superclass interfaces when new
6823// interfaces are added in subclass's interface tables.
6824//
6825// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6826// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6827// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6828// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006829static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006830 size_t super_ifcount,
Stephen Hines48ba1972018-09-24 13:35:54 -07006831 const std::vector<ObjPtr<mirror::Class>>& to_process)
Alex Lighteb7c1442015-08-31 13:17:42 -07006832 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006833 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006834 // This is the set of all class's already in the iftable. Used to make checking if a class has
6835 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006836 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006837 // The first super_ifcount elements are from the superclass. We note that they are already added.
6838 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006839 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006840 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6841 classes_in_iftable.insert(iface);
6842 }
6843 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006844 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006845 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6846 // At this point in the loop current-iface-list has the invariant that:
6847 // for every pair of interfaces I,J within it:
6848 // if index_of(I) < index_of(J) then I is not a subtype of J
6849
6850 // If we have already seen this element then all of its super-interfaces must already be in the
6851 // current-iface-list so we can skip adding it.
6852 if (!ContainsElement(classes_in_iftable, interface)) {
6853 // We haven't seen this interface so add all of its super-interfaces onto the
6854 // current-iface-list, skipping those already on it.
6855 int32_t ifcount = interface->GetIfTableCount();
6856 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006857 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006858 if (!ContainsElement(classes_in_iftable, super_interface)) {
6859 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6860 classes_in_iftable.insert(super_interface);
6861 iftable->SetInterface(filled_ifcount, super_interface);
6862 filled_ifcount++;
6863 }
6864 }
6865 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6866 // Place this interface onto the current-iface-list after all of its super-interfaces.
6867 classes_in_iftable.insert(interface);
6868 iftable->SetInterface(filled_ifcount, interface);
6869 filled_ifcount++;
6870 } else if (kIsDebugBuild) {
6871 // Check all super-interfaces are already in the list.
6872 int32_t ifcount = interface->GetIfTableCount();
6873 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006874 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006875 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07006876 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
6877 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006878 }
6879 }
6880 }
6881 if (kIsDebugBuild) {
6882 // Check that the iftable is ordered correctly.
6883 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006884 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006885 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006886 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006887 // !(if_a <: if_b)
6888 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07006889 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
6890 << ") extends "
6891 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07006892 << "interface list.";
6893 }
6894 }
6895 }
6896 return filled_ifcount;
6897}
6898
6899bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6900 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6901 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08006902 const bool has_superclass = klass->HasSuperClass();
6903 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08006904 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006905 const size_t num_interfaces =
6906 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006907 if (num_interfaces == 0) {
6908 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08006909 if (LIKELY(has_superclass)) {
6910 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
6911 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006912 // Class implements no interfaces.
6913 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006914 return true;
6915 }
Ian Rogers9bc81912012-10-11 21:43:36 -07006916 // Class implements same interfaces as parent, are any of these not marker interfaces?
6917 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006918 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006919 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006920 if (super_iftable->GetMethodArrayCount(i) > 0) {
6921 has_non_marker_interface = true;
6922 break;
6923 }
6924 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006925 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07006926 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07006927 klass->SetIfTable(super_iftable);
6928 return true;
6929 }
6930 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006931 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07006932 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006933 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006934 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006935 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00006936 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006937 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006938 if (UNLIKELY(!interface->IsInterface())) {
6939 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006940 ThrowIncompatibleClassChangeError(klass.Get(),
6941 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07006942 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006943 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
6944 return false;
6945 }
6946 ifcount += interface->GetIfTableCount();
6947 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006948 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006949 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006950 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006951 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006952 return false;
6953 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006954 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006955 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006956 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006957 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006958 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07006959 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07006960 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006961 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006962
6963 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
6964 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
6965 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07006966 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006967
6968 size_t new_ifcount;
6969 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07006970 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Vladimir Markobcf17522018-06-01 13:14:32 +01006971 std::vector<ObjPtr<mirror::Class>> to_add;
Alex Lighteb7c1442015-08-31 13:17:42 -07006972 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07006973 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00006974 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Vladimir Markobcf17522018-06-01 13:14:32 +01006975 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08006976 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006977
6978 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006979 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006980
Ian Rogers7b078e82014-09-10 14:44:24 -07006981 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006982
Ian Rogersb52b01a2012-01-12 17:01:38 -08006983 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07006984 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006985 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01006986 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Alex Lighteb7c1442015-08-31 13:17:42 -07006987 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006988 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006989 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006990 return false;
6991 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006992 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08006993 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006994 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08006995 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006996 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07006997 return true;
6998}
6999
Alex Light1f3925d2016-09-07 12:04:20 -07007000// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7001// of methods must be unique.
7002static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7003 return nullptr;
7004}
7005
7006template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007007static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007008 const ScopedArenaVector<ArtMethod*>& list,
7009 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007010 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007011 for (ArtMethod* method : list) {
7012 if (cmp.HasSameNameAndSignature(method)) {
7013 return method;
7014 }
7015 }
Alex Light1f3925d2016-09-07 12:04:20 -07007016 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007017}
7018
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007019namespace {
7020
Alex Light1f3925d2016-09-07 12:04:20 -07007021// Check that all vtable entries are present in this class's virtuals or are the same as a
7022// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007023void CheckClassOwnsVTableEntries(Thread* self,
7024 Handle<mirror::Class> klass,
7025 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007026 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007027 StackHandleScope<2> hs(self);
7028 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007029 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007030 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007031 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007032 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7033 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7034 CHECK(m != nullptr);
7035
Alex Lighta41a30782017-03-29 11:33:19 -07007036 if (m->GetMethodIndexDuringLinking() != i) {
7037 LOG(WARNING) << m->PrettyMethod()
7038 << " has an unexpected method index for its spot in the vtable for class"
7039 << klass->PrettyClass();
7040 }
Alex Lighte64300b2015-12-15 15:02:47 -08007041 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7042 auto is_same_method = [m] (const ArtMethod& meth) {
7043 return &meth == m;
7044 };
Alex Light3f980532017-03-17 15:10:32 -07007045 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7046 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7047 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7048 << klass->PrettyClass() << " or any of its superclasses!";
7049 }
Alex Lighte64300b2015-12-15 15:02:47 -08007050 }
7051}
7052
Alex Light1f3925d2016-09-07 12:04:20 -07007053// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7054// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007055template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007056void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007057 REQUIRES_SHARED(Locks::mutator_lock_) {
7058 StackHandleScope<1> hs(self);
7059 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7060 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007061
7062 // Observations:
7063 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7064 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7065 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7066 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7067 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7068 // * The single-pass algorithm will trade memory for speed, but that is OK.
7069
7070 CHECK_GT(num_entries, 0);
7071
7072 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7073 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7074 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7075 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7076 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7077 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7078 << m2->PrettyMethod() << " (0x" << std::hex
7079 << reinterpret_cast<uintptr_t>(m2) << ")";
7080 };
7081 struct BaseHashType {
7082 static size_t HashCombine(size_t seed, size_t val) {
7083 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7084 }
7085 };
7086
7087 // Check assuming all entries come from the same dex file.
7088 {
7089 // Find the first interesting method and its dex file.
7090 int32_t start = 0;
7091 for (; start < num_entries; ++start) {
7092 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7093 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7094 // maybe).
7095 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7096 vtable_entry->GetAccessFlags())) {
7097 continue;
7098 }
7099 break;
7100 }
7101 if (start == num_entries) {
7102 return;
7103 }
7104 const DexFile* dex_file =
7105 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7106 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7107
7108 // Helper function to avoid logging if we have to run the cross-file checks.
7109 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7110 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7111 using PairType = std::pair<uint32_t, uint16_t>;
7112 struct PairHash : BaseHashType {
7113 size_t operator()(const PairType& key) const {
7114 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7115 }
7116 };
7117 std::unordered_map<PairType, int32_t, PairHash> seen;
7118 seen.reserve(2 * num_entries);
7119 bool need_slow_path = false;
7120 bool found_dup = false;
7121 for (int i = start; i < num_entries; ++i) {
7122 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7123 // wrt/ kPointerSize.
7124 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7125 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7126 vtable_entry->GetAccessFlags())) {
7127 continue;
7128 }
7129 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7130 if (dex_file != m->GetDexFile()) {
7131 need_slow_path = true;
7132 break;
7133 }
7134 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7135 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7136 auto it = seen.find(pair);
7137 if (it != seen.end()) {
7138 found_dup = true;
7139 if (log_warn) {
7140 log_fn(it->second, i);
7141 }
7142 } else {
7143 seen.emplace(pair, i);
7144 }
7145 }
7146 return std::make_pair(need_slow_path, found_dup);
7147 };
7148 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7149 if (!result.first) {
7150 if (result.second) {
7151 check_fn(/* log_warn= */ true);
7152 }
7153 return;
7154 }
7155 }
7156
7157 // Need to check across dex files.
7158 struct Entry {
7159 size_t cached_hash = 0;
7160 const char* name = nullptr;
7161 Signature signature = Signature::NoSignature();
7162 uint32_t name_len = 0;
7163
7164 Entry(const DexFile* dex_file, const dex::MethodId& mid)
7165 : name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
7166 signature(dex_file->GetMethodSignature(mid)) {
7167 }
7168
7169 bool operator==(const Entry& other) const {
7170 if (name_len != other.name_len || strcmp(name, other.name) != 0) {
7171 return false;
7172 }
7173 return signature == other.signature;
7174 }
7175 };
7176 struct EntryHash {
7177 size_t operator()(const Entry& key) const {
7178 return key.cached_hash;
7179 }
7180 };
7181 std::unordered_map<Entry, int32_t, EntryHash> map;
7182 for (int32_t i = 0; i < num_entries; ++i) {
7183 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7184 // wrt/ kPointerSize.
7185 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7186 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7187 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007188 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7189 vtable_entry->GetAccessFlags())) {
7190 continue;
7191 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007192 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7193 const DexFile* dex_file = m->GetDexFile();
7194 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7195
7196 Entry e(dex_file, mid);
7197
7198 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7199 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7200 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7201 sig_hash);
7202
7203 auto it = map.find(e);
7204 if (it != map.end()) {
7205 log_fn(it->second, i);
7206 } else {
7207 map.emplace(e, i);
Alex Light1f3925d2016-09-07 12:04:20 -07007208 }
7209 }
7210}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007211
7212void CheckVTableHasNoDuplicates(Thread* self,
7213 Handle<mirror::Class> klass,
7214 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007215 REQUIRES_SHARED(Locks::mutator_lock_) {
7216 switch (pointer_size) {
7217 case PointerSize::k64:
7218 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7219 break;
7220 case PointerSize::k32:
7221 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7222 break;
7223 }
7224}
Alex Light1f3925d2016-09-07 12:04:20 -07007225
7226static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
7227 REQUIRES_SHARED(Locks::mutator_lock_) {
7228 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7229 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7230}
7231
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007232} // namespace
7233
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007234void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7235 ArtMethod* unimplemented_method,
7236 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007237 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007238 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007239 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007240 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007241 if (super_class->ShouldHaveImt()) {
7242 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7243 for (size_t i = 0; i < ImTable::kSize; ++i) {
7244 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007245 }
7246 } else {
7247 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007248 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007249 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007250 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007251 FillIMTFromIfTable(if_table,
7252 unimplemented_method,
7253 imt_conflict_method,
7254 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007255 /*create_conflict_tables=*/false,
7256 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007257 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007258 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007259 }
7260 }
7261}
7262
Vladimir Marko921094a2017-01-12 18:37:06 +00007263class ClassLinker::LinkInterfaceMethodsHelper {
7264 public:
7265 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7266 Handle<mirror::Class> klass,
7267 Thread* self,
7268 Runtime* runtime)
7269 : class_linker_(class_linker),
7270 klass_(klass),
7271 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7272 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7273 self_(self),
7274 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7275 allocator_(&stack_),
7276 default_conflict_methods_(allocator_.Adapter()),
7277 overriding_default_conflict_methods_(allocator_.Adapter()),
7278 miranda_methods_(allocator_.Adapter()),
7279 default_methods_(allocator_.Adapter()),
7280 overriding_default_methods_(allocator_.Adapter()),
7281 move_table_(allocator_.Adapter()) {
7282 }
7283
7284 ArtMethod* FindMethod(ArtMethod* interface_method,
7285 MethodNameAndSignatureComparator& interface_name_comparator,
7286 ArtMethod* vtable_impl)
7287 REQUIRES_SHARED(Locks::mutator_lock_);
7288
7289 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7290 MethodNameAndSignatureComparator& interface_name_comparator)
7291 REQUIRES_SHARED(Locks::mutator_lock_);
7292
7293 bool HasNewVirtuals() const {
7294 return !(miranda_methods_.empty() &&
7295 default_methods_.empty() &&
7296 overriding_default_methods_.empty() &&
7297 overriding_default_conflict_methods_.empty() &&
7298 default_conflict_methods_.empty());
7299 }
7300
7301 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7302
7303 ObjPtr<mirror::PointerArray> UpdateVtable(
7304 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7305 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
7306
7307 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7308
7309 void UpdateIMT(ArtMethod** out_imt);
7310
7311 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7312 if (kIsDebugBuild) {
7313 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7314 // Check that there are no stale methods are in the dex cache array.
7315 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7316 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007317 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7318 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007319 CHECK(move_table_.find(m) == move_table_.end() ||
7320 // The original versions of copied methods will still be present so allow those too.
7321 // Note that if the first check passes this might fail to GetDeclaringClass().
7322 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7323 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7324 [m] (ArtMethod& meth) {
7325 return &meth == m;
7326 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7327 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7328 }
7329 }
7330 }
7331
7332 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7333 LengthPrefixedArray<ArtMethod>* methods) {
7334 if (kIsDebugBuild) {
7335 CHECK(methods != nullptr);
7336 // Put some random garbage in old methods to help find stale pointers.
7337 if (methods != old_methods && old_methods != nullptr) {
7338 // Need to make sure the GC is not running since it could be scanning the methods we are
7339 // about to overwrite.
7340 ScopedThreadStateChange tsc(self_, kSuspended);
7341 gc::ScopedGCCriticalSection gcs(self_,
7342 gc::kGcCauseClassLinker,
7343 gc::kCollectorTypeClassLinker);
7344 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7345 method_size_,
7346 method_alignment_);
7347 memset(old_methods, 0xFEu, old_size);
7348 }
7349 }
7350 }
7351
7352 private:
7353 size_t NumberOfNewVirtuals() const {
7354 return miranda_methods_.size() +
7355 default_methods_.size() +
7356 overriding_default_conflict_methods_.size() +
7357 overriding_default_methods_.size() +
7358 default_conflict_methods_.size();
7359 }
7360
7361 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7362 return !klass_->IsInterface();
7363 }
7364
7365 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7366 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7367 << "Interfaces should only have default-conflict methods appended to them.";
7368 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7369 << miranda_methods_.size()
7370 << " default_methods=" << default_methods_.size()
7371 << " overriding_default_methods=" << overriding_default_methods_.size()
7372 << " default_conflict_methods=" << default_conflict_methods_.size()
7373 << " overriding_default_conflict_methods="
7374 << overriding_default_conflict_methods_.size();
7375 }
7376
7377 ClassLinker* class_linker_;
7378 Handle<mirror::Class> klass_;
7379 size_t method_alignment_;
7380 size_t method_size_;
7381 Thread* const self_;
7382
7383 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7384 // the virtual methods array.
7385 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7386 // during cross compilation.
7387 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7388 ArenaStack stack_;
7389 ScopedArenaAllocator allocator_;
7390
7391 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7392 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7393 ScopedArenaVector<ArtMethod*> miranda_methods_;
7394 ScopedArenaVector<ArtMethod*> default_methods_;
7395 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7396
7397 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7398};
7399
7400ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7401 ArtMethod* interface_method,
7402 MethodNameAndSignatureComparator& interface_name_comparator,
7403 ArtMethod* vtable_impl) {
7404 ArtMethod* current_method = nullptr;
7405 switch (class_linker_->FindDefaultMethodImplementation(self_,
7406 interface_method,
7407 klass_,
7408 /*out*/&current_method)) {
7409 case DefaultMethodSearchResult::kDefaultConflict: {
7410 // Default method conflict.
7411 DCHECK(current_method == nullptr);
7412 ArtMethod* default_conflict_method = nullptr;
7413 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7414 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7415 default_conflict_method = vtable_impl;
7416 } else {
7417 // See if we already have a conflict method for this method.
7418 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7419 interface_name_comparator,
7420 default_conflict_methods_,
7421 overriding_default_conflict_methods_);
7422 if (LIKELY(preexisting_conflict != nullptr)) {
7423 // We already have another conflict we can reuse.
7424 default_conflict_method = preexisting_conflict;
7425 } else {
7426 // Note that we do this even if we are an interface since we need to create this and
7427 // cannot reuse another classes.
7428 // Create a new conflict method for this to use.
7429 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7430 new(default_conflict_method) ArtMethod(interface_method,
7431 class_linker_->GetImagePointerSize());
7432 if (vtable_impl == nullptr) {
7433 // Save the conflict method. We need to add it to the vtable.
7434 default_conflict_methods_.push_back(default_conflict_method);
7435 } else {
7436 // Save the conflict method but it is already in the vtable.
7437 overriding_default_conflict_methods_.push_back(default_conflict_method);
7438 }
7439 }
7440 }
7441 current_method = default_conflict_method;
7442 break;
7443 } // case kDefaultConflict
7444 case DefaultMethodSearchResult::kDefaultFound: {
7445 DCHECK(current_method != nullptr);
7446 // Found a default method.
7447 if (vtable_impl != nullptr &&
7448 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7449 // We found a default method but it was the same one we already have from our
7450 // superclass. Don't bother adding it to our vtable again.
7451 current_method = vtable_impl;
7452 } else if (LIKELY(FillTables())) {
7453 // Interfaces don't need to copy default methods since they don't have vtables.
7454 // Only record this default method if it is new to save space.
7455 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7456 // would make lookup for interface super much faster. (We would only need to scan
7457 // the iftable to find if there is a NSME or AME.)
7458 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7459 default_methods_,
7460 overriding_default_methods_);
7461 if (old == nullptr) {
7462 // We found a default method implementation and there were no conflicts.
7463 if (vtable_impl == nullptr) {
7464 // Save the default method. We need to add it to the vtable.
7465 default_methods_.push_back(current_method);
7466 } else {
7467 // Save the default method but it is already in the vtable.
7468 overriding_default_methods_.push_back(current_method);
7469 }
7470 } else {
7471 CHECK(old == current_method) << "Multiple default implementations selected!";
7472 }
7473 }
7474 break;
7475 } // case kDefaultFound
7476 case DefaultMethodSearchResult::kAbstractFound: {
7477 DCHECK(current_method == nullptr);
7478 // Abstract method masks all defaults.
7479 if (vtable_impl != nullptr &&
7480 vtable_impl->IsAbstract() &&
7481 !vtable_impl->IsDefaultConflicting()) {
7482 // We need to make this an abstract method but the version in the vtable already is so
7483 // don't do anything.
7484 current_method = vtable_impl;
7485 }
7486 break;
7487 } // case kAbstractFound
7488 }
7489 return current_method;
7490}
7491
7492ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7493 ArtMethod* interface_method,
7494 MethodNameAndSignatureComparator& interface_name_comparator) {
7495 // Find out if there is already a miranda method we can use.
7496 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7497 miranda_methods_);
7498 if (miranda_method == nullptr) {
7499 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7500 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7501 CHECK(miranda_method != nullptr);
7502 // Point the interface table at a phantom slot.
7503 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7504 miranda_methods_.push_back(miranda_method);
7505 }
7506 return miranda_method;
7507}
7508
7509void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7510 LogNewVirtuals();
7511
7512 const size_t old_method_count = klass_->NumMethods();
7513 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7514 DCHECK_NE(old_method_count, new_method_count);
7515
7516 // Attempt to realloc to save RAM if possible.
7517 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7518 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7519 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7520 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7521 // CopyFrom has internal read barriers.
7522 //
7523 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7524 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7525 method_size_,
7526 method_alignment_);
7527 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7528 method_size_,
7529 method_alignment_);
7530 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7531 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007532 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007533 self_, old_methods, old_methods_ptr_size, new_size));
7534 CHECK(methods != nullptr); // Native allocation failure aborts.
7535
7536 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7537 if (methods != old_methods) {
7538 // Maps from heap allocated miranda method to linear alloc miranda method.
7539 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7540 // Copy over the old methods.
7541 for (auto& m : klass_->GetMethods(pointer_size)) {
7542 move_table_.emplace(&m, &*out);
7543 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7544 // barriers when it copies.
7545 out->CopyFrom(&m, pointer_size);
7546 ++out;
7547 }
7548 }
7549 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7550 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7551 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007552 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7553 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007554 ArtMethod& new_method = *out;
7555 new_method.CopyFrom(mir_method, pointer_size);
7556 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7557 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7558 << "Miranda method should be abstract!";
7559 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007560 // Update the entry in the method array, as the array will be used for future lookups,
7561 // where thread suspension is allowed.
7562 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7563 // would not see them.
7564 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007565 ++out;
7566 }
7567 // We need to copy the default methods into our own method table since the runtime requires that
7568 // every method on a class's vtable be in that respective class's virtual method table.
7569 // NOTE This means that two classes might have the same implementation of a method from the same
7570 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7571 // default method found on a class with one found on the declaring interface directly and must
7572 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007573 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7574 &overriding_default_methods_}) {
7575 for (size_t i = 0; i < methods_vec->size(); ++i) {
7576 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007577 ArtMethod& new_method = *out;
7578 new_method.CopyFrom(def_method, pointer_size);
7579 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7580 // verified yet it shouldn't have methods that are skipping access checks.
7581 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7582 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007583 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007584 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7585 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7586 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7587 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007588 // Update the entry in the method array, as the array will be used for future lookups,
7589 // where thread suspension is allowed.
7590 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7591 // would not see them.
7592 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007593 ++out;
7594 }
7595 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007596 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7597 &overriding_default_conflict_methods_}) {
7598 for (size_t i = 0; i < methods_vec->size(); ++i) {
7599 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007600 ArtMethod& new_method = *out;
7601 new_method.CopyFrom(conf_method, pointer_size);
7602 // This is a type of default method (there are default method impls, just a conflict) so
7603 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7604 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7605 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007606 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
7607 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007608 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007609 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007610 constexpr uint32_t kMaskFlags =
7611 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00007612 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7613 DCHECK(new_method.IsDefaultConflicting());
7614 // The actual method might or might not be marked abstract since we just copied it from a
7615 // (possibly default) interface method. We need to set it entry point to be the bridge so
7616 // that the compiler will not invoke the implementation of whatever method we copied from.
7617 EnsureThrowsInvocationError(class_linker_, &new_method);
7618 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007619 // Update the entry in the method array, as the array will be used for future lookups,
7620 // where thread suspension is allowed.
7621 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7622 // would not see them.
7623 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007624 ++out;
7625 }
7626 }
7627 methods->SetSize(new_method_count);
7628 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7629}
7630
7631ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7632 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7633 ObjPtr<mirror::PointerArray> old_vtable) {
7634 // Update the vtable to the new method structures. We can skip this for interfaces since they
7635 // do not have vtables.
7636 const size_t old_vtable_count = old_vtable->GetLength();
7637 const size_t new_vtable_count = old_vtable_count +
7638 miranda_methods_.size() +
7639 default_methods_.size() +
7640 default_conflict_methods_.size();
7641
7642 ObjPtr<mirror::PointerArray> vtable =
Vladimir Markobcf17522018-06-01 13:14:32 +01007643 ObjPtr<mirror::PointerArray>::DownCast(old_vtable->CopyOf(self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007644 if (UNLIKELY(vtable == nullptr)) {
7645 self_->AssertPendingOOMException();
7646 return nullptr;
7647 }
7648
7649 size_t vtable_pos = old_vtable_count;
7650 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7651 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7652 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7653 default_conflict_methods_,
7654 miranda_methods_}) {
7655 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007656 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007657 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7658 // fields are references into the dex file the method was defined in. Since the ArtMethod
7659 // does not store that information it uses declaring_class_->dex_cache_.
7660 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7661 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7662 ++vtable_pos;
7663 }
7664 }
7665 DCHECK_EQ(vtable_pos, new_vtable_count);
7666
7667 // Update old vtable methods. We use the default_translations map to figure out what each
7668 // vtable entry should be updated to, if they need to be at all.
7669 for (size_t i = 0; i < old_vtable_count; ++i) {
7670 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7671 // Try and find what we need to change this method to.
7672 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007673 if (translation_it != default_translations.end()) {
7674 if (translation_it->second.IsInConflict()) {
7675 // Find which conflict method we are to use for this method.
7676 MethodNameAndSignatureComparator old_method_comparator(
7677 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7678 // We only need to look through overriding_default_conflict_methods since this is an
7679 // overridden method we are fixing up here.
7680 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7681 old_method_comparator, overriding_default_conflict_methods_);
7682 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7683 translated_method = new_conflict_method;
7684 } else if (translation_it->second.IsAbstract()) {
7685 // Find which miranda method we are to use for this method.
7686 MethodNameAndSignatureComparator old_method_comparator(
7687 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7688 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7689 miranda_methods_);
7690 DCHECK(miranda_method != nullptr);
7691 translated_method = miranda_method;
7692 } else {
7693 // Normal default method (changed from an older default or abstract interface method).
7694 DCHECK(translation_it->second.IsTranslation());
7695 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007696 auto it = move_table_.find(translated_method);
7697 DCHECK(it != move_table_.end());
7698 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007699 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007700 } else {
7701 auto it = move_table_.find(translated_method);
7702 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007703 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007704
7705 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007706 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007707 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007708 if (kIsDebugBuild) {
7709 auto* methods = klass_->GetMethodsPtr();
7710 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007711 reinterpret_cast<uintptr_t>(translated_method));
7712 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007713 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7714 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007715 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007716 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007717 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007718 }
7719 }
Vladimir Markod93e3742018-07-18 10:58:13 +01007720 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00007721 return vtable;
7722}
7723
7724void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7725 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7726 const size_t ifcount = klass_->GetIfTableCount();
7727 // Go fix up all the stale iftable pointers.
7728 for (size_t i = 0; i < ifcount; ++i) {
7729 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
7730 auto* method_array = iftable->GetMethodArray(i);
7731 auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
7732 DCHECK(m != nullptr) << klass_->PrettyClass();
7733 auto it = move_table_.find(m);
7734 if (it != move_table_.end()) {
7735 auto* new_m = it->second;
7736 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7737 method_array->SetElementPtrSize(j, new_m, pointer_size);
7738 }
7739 }
7740 }
7741}
7742
7743void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7744 // Fix up IMT next.
7745 for (size_t i = 0; i < ImTable::kSize; ++i) {
7746 auto it = move_table_.find(out_imt[i]);
7747 if (it != move_table_.end()) {
7748 out_imt[i] = it->second;
7749 }
7750 }
7751}
7752
Alex Light705ad492015-09-21 11:36:30 -07007753// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007754bool ClassLinker::LinkInterfaceMethods(
7755 Thread* self,
7756 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007757 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007758 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007759 ArtMethod** out_imt) {
7760 StackHandleScope<3> hs(self);
7761 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007762
7763 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007764 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007765 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007766 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007767 const size_t ifcount = klass->GetIfTableCount();
7768
Vladimir Marko921094a2017-01-12 18:37:06 +00007769 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007770
7771 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7772 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007773 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007774 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007775 const bool extend_super_iftable = has_superclass;
7776 if (has_superclass && fill_tables) {
7777 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007778 unimplemented_method,
7779 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007780 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007781 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007782 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007783 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7784 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007785 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007786 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7787 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007788 }
7789 }
7790
Vladimir Marko921094a2017-01-12 18:37:06 +00007791 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7792
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007793 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007794 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007795 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7796 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7797 // they will already be null. This has the additional benefit that the declarer of a miranda
7798 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007799 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007800 --i;
Alex Light9139e002015-10-09 15:59:48 -07007801 DCHECK_LT(i, ifcount);
7802
Alex Light705ad492015-09-21 11:36:30 -07007803 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007804 if (num_methods > 0) {
7805 StackHandleScope<2> hs2(self);
7806 const bool is_super = i < super_ifcount;
7807 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007808 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7809 // conflict methods. Just set this as nullptr in those cases.
7810 Handle<mirror::PointerArray> method_array(fill_tables
7811 ? hs2.NewHandle(iftable->GetMethodArray(i))
7812 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007813
Alex Lighte64300b2015-12-15 15:02:47 -08007814 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007815 ScopedNullHandle<mirror::PointerArray> null_handle;
7816 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007817 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007818
Alex Light9139e002015-10-09 15:59:48 -07007819 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7820 // and confusing. Default methods should always look through all the superclasses
7821 // because they are the last choice of an implementation. We get around this by looking
7822 // at the super-classes iftable methods (copied into method_array previously) when we are
7823 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007824 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007825 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007826 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007827 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007828 using_virtuals = true;
7829 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7830 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007831 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007832 // For a new interface, however, we need the whole vtable in case a new
7833 // interface method is implemented in the whole superclass.
7834 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007835 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007836 input_vtable_array = vtable;
7837 input_array_length = input_vtable_array->GetLength();
7838 }
Alex Lighte64300b2015-12-15 15:02:47 -08007839
Alex Lighteb7c1442015-08-31 13:17:42 -07007840 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007841 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007842 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007843 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007844 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00007845 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07007846 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007847 // For each method listed in the interface's method list, find the
7848 // matching method in our class's method list. We want to favor the
7849 // subclass over the superclass, which just requires walking
7850 // back from the end of the vtable. (This only matters if the
7851 // superclass defines a private method and this class redefines
7852 // it -- otherwise it would use the same vtable slot. In .dex files
7853 // those don't end up in the virtual method table, so it shouldn't
7854 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007855 //
7856 // To find defaults we need to do the same but also go over interfaces.
7857 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007858 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007859 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007860 ArtMethod* vtable_method = using_virtuals ?
7861 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007862 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7863 ArtMethod* vtable_method_for_name_comparison =
7864 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007865 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007866 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007867 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007868 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7869 // allocations.
7870 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007871 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007872 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007873 vtable_method->PrettyMethod().c_str(),
7874 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07007875 return false;
Alex Light9139e002015-10-09 15:59:48 -07007876 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007877 // We might have a newer, better, default method for this, so we just skip it. If we
7878 // are still using this we will select it again when scanning for default methods. To
7879 // obviate the need to copy the method again we will make a note that we already found
7880 // a default here.
7881 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07007882 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07007883 break;
7884 } else {
7885 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07007886 if (LIKELY(fill_tables)) {
7887 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
7888 // Place method in imt if entry is empty, place conflict otherwise.
7889 SetIMTRef(unimplemented_method,
7890 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07007891 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007892 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07007893 /*out*/imt_ptr);
7894 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007895 break;
7896 }
7897 }
Alex Light9139e002015-10-09 15:59:48 -07007898 }
7899 // Continue on to the next method if we are done.
7900 if (LIKELY(found_impl)) {
7901 continue;
7902 } else if (LIKELY(super_interface)) {
7903 // Don't look for a default implementation when the super-method is implemented directly
7904 // by the class.
7905 //
7906 // See if we can use the superclasses method and skip searching everything else.
7907 // Note: !found_impl && super_interface
7908 CHECK(extend_super_iftable);
7909 // If this is a super_interface method it is possible we shouldn't override it because a
7910 // superclass could have implemented it directly. We get the method the superclass used
7911 // to implement this to know if we can override it with a default method. Doing this is
7912 // safe since we know that the super_iftable is filled in so we can simply pull it from
7913 // there. We don't bother if this is not a super-classes interface since in that case we
7914 // have scanned the entire vtable anyway and would have found it.
7915 // TODO This is rather dirty but it is faster than searching through the entire vtable
7916 // every time.
7917 ArtMethod* supers_method =
7918 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7919 DCHECK(supers_method != nullptr);
7920 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07007921 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07007922 // The method is not overridable by a default method (i.e. it is directly implemented
7923 // in some class). Therefore move onto the next interface method.
7924 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007925 } else {
7926 // If the super-classes method is override-able by a default method we need to keep
7927 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
7928 // If it turns out not to be overridden and we did not keep track of it we might add it
Alex Light66630be2016-05-04 09:23:09 -07007929 // to the vtable twice, causing corruption (vtable entries having inconsistent and
7930 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
7931 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007932 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07007933 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
7934 << " and not 'nullptr' or "
7935 << supers_method->PrettyMethod()
7936 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07007937 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07007938 }
7939 }
7940 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00007941 ArtMethod* current_method = helper.FindMethod(interface_method,
7942 interface_name_comparator,
7943 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07007944 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08007945 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07007946 // We could not find an implementation for this method and since it is a brand new
7947 // interface we searched the entire vtable (and all default methods) for an
7948 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00007949 current_method = helper.GetOrCreateMirandaMethod(interface_method,
7950 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08007951 }
7952
7953 if (current_method != nullptr) {
7954 // We found a default method implementation. Record it in the iftable and IMT.
7955 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
7956 SetIMTRef(unimplemented_method,
7957 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08007958 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007959 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08007960 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07007961 }
7962 }
Alex Light705ad492015-09-21 11:36:30 -07007963 } // For each method in interface end.
7964 } // if (num_methods > 0)
7965 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07007966 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00007967 if (helper.HasNewVirtuals()) {
7968 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7969 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
7970 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
7971
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007972 // Done copying methods, they are all roots in the class now, so we can end the no thread
Mathieu Chartiere401d142015-04-22 13:56:20 -07007973 // suspension assert.
7974 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07007975
Alex Light705ad492015-09-21 11:36:30 -07007976 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007977 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007978 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007979 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07007980 return false;
7981 }
Vladimir Marko921094a2017-01-12 18:37:06 +00007982 helper.UpdateIfTable(iftable);
7983 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007984 }
Alex Light705ad492015-09-21 11:36:30 -07007985
Vladimir Marko921094a2017-01-12 18:37:06 +00007986 helper.CheckNoStaleMethodsInDexCache();
7987 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007988 } else {
7989 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007990 }
Alex Light705ad492015-09-21 11:36:30 -07007991 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07007992 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07007993 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007994 return true;
7995}
7996
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007997bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08007998 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007999 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008000}
8001
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008002bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008003 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008004 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008005}
8006
Brian Carlstromdbc05252011-09-09 01:59:59 -07008007struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08008008 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07008009 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07008010 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008011 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08008012 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07008013 // First come reference fields, then 64-bit, then 32-bit, and then 16-bit, then finally 8-bit.
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07008014 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
8015 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08008016 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00008017 if (type1 == Primitive::kPrimNot) {
8018 // Reference always goes first.
8019 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08008020 }
Vladimir Markod5777482014-11-12 17:02:02 +00008021 if (type2 == Primitive::kPrimNot) {
8022 // Reference always goes first.
8023 return false;
8024 }
8025 size_t size1 = Primitive::ComponentSize(type1);
8026 size_t size2 = Primitive::ComponentSize(type2);
8027 if (size1 != size2) {
8028 // Larger primitive types go first.
8029 return size1 > size2;
8030 }
8031 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
8032 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008033 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008034 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
8035 // by name and for equal names by type id index.
8036 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
8037 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07008038 }
8039};
8040
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008041bool ClassLinker::LinkFields(Thread* self,
8042 Handle<mirror::Class> klass,
8043 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008044 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008045 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008046 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008047 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8048 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008049
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008050 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008051 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008052 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008053 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008054 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008055 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008056 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008057 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008058 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008059 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008060 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008061 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008062
David Sehr709b0702016-10-13 09:12:37 -07008063 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008064
Brian Carlstromdbc05252011-09-09 01:59:59 -07008065 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008066 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008067 //
8068 // The overall sort order order is:
8069 // 1) All object reference fields, sorted alphabetically.
8070 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8071 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8072 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8073 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8074 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8075 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8076 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8077 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8078 //
8079 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
8080 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008081 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008082 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07008083 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07008084 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008085 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008086 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07008087 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
8088 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07008089
Fred Shih381e4ca2014-08-25 17:24:27 -07008090 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07008091 size_t current_field = 0;
8092 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07008093 FieldGaps gaps;
8094
Brian Carlstromdbc05252011-09-09 01:59:59 -07008095 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008096 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07008097 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07008098 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008099 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07008100 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008101 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008102 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
8103 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07008104 MemberOffset old_offset = field_offset;
8105 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
8106 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
8107 }
Roland Levillain14d90572015-07-16 10:52:26 +01008108 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008109 grouped_and_sorted_fields.pop_front();
8110 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008111 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00008112 field_offset = MemberOffset(field_offset.Uint32Value() +
8113 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008114 }
Fred Shih381e4ca2014-08-25 17:24:27 -07008115 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
8116 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00008117 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8118 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8119 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8120 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07008121 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
8122 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07008123 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008124
Elliott Hughesadb460d2011-10-05 17:02:34 -07008125 // 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 -07008126 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008127 // We know there are no non-reference fields in the Reference classes, and we know
8128 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008129 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008130 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008131 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008132 --num_reference_fields;
8133 }
8134
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008135 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008136 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008137 if (is_static) {
8138 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008139 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008140 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008141 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008142 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008143 if (num_reference_fields == 0 || super_class == nullptr) {
8144 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008145 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008146 if (super_class == nullptr ||
8147 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8148 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008149 }
8150 }
8151 if (kIsDebugBuild) {
8152 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8153 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008154 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008155 while (cur_super != nullptr) {
8156 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8157 cur_super = cur_super->GetSuperClass();
8158 }
8159 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008160 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008161 } else {
8162 // Check that there is at least num_reference_fields other than Object.class.
8163 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008164 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008165 }
8166 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008167 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008168 std::string temp;
8169 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8170 size_t previous_size = klass->GetObjectSize();
8171 if (previous_size != 0) {
8172 // Make sure that we didn't originally have an incorrect size.
8173 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008174 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008175 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008176 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008177 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008178
8179 if (kIsDebugBuild) {
8180 // Make sure that the fields array is ordered by name but all reference
8181 // offsets are at the beginning as far as alignment allows.
8182 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008183 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008184 : klass->GetFirstReferenceInstanceFieldOffset();
8185 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8186 num_reference_fields *
8187 sizeof(mirror::HeapReference<mirror::Object>));
8188 MemberOffset current_ref_offset = start_ref_offset;
8189 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008190 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008191 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008192 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8193 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008194 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008195 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008196 // NOTE: The field names can be the same. This is not possible in the Java language
8197 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008198 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008199 }
8200 Primitive::Type type = field->GetTypeAsPrimitiveType();
8201 bool is_primitive = type != Primitive::kPrimNot;
8202 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8203 strcmp("referent", field->GetName()) == 0) {
8204 is_primitive = true; // We lied above, so we have to expect a lie here.
8205 }
8206 MemberOffset offset = field->GetOffsetDuringLinking();
8207 if (is_primitive) {
8208 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8209 // Shuffled before references.
8210 size_t type_size = Primitive::ComponentSize(type);
8211 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8212 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8213 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8214 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8215 }
8216 } else {
8217 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8218 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8219 sizeof(mirror::HeapReference<mirror::Object>));
8220 }
8221 }
8222 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8223 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008224 return true;
8225}
8226
Vladimir Marko76649e82014-11-10 18:32:59 +00008227// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008228void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008229 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008230 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008231 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008232 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008233 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008234 // Compute reference offsets unless our superclass overflowed.
8235 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8236 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008237 if (num_reference_fields != 0u) {
8238 // All of the fields that contain object references are guaranteed be grouped in memory
8239 // starting at an appropriately aligned address after super class object data.
8240 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8241 sizeof(mirror::HeapReference<mirror::Object>));
8242 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008243 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008244 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008245 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008246 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008247 reference_offsets |= (0xffffffffu << start_bit) &
8248 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008249 }
8250 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008251 }
8252 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008253 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008254}
8255
Vladimir Marko18090d12018-06-01 16:53:12 +01008256ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8257 ObjPtr<mirror::DexCache> dex_cache) {
8258 StackHandleScope<1> hs(Thread::Current());
8259 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8260 return DoResolveString(string_idx, h_dex_cache);
8261}
8262
8263ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8264 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008265 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008266 uint32_t utf16_length;
8267 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008268 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008269 if (string != nullptr) {
8270 dex_cache->SetResolvedString(string_idx, string);
8271 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008272 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008273}
8274
Vladimir Marko18090d12018-06-01 16:53:12 +01008275ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8276 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008277 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008278 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008279 uint32_t utf16_length;
8280 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008281 ObjPtr<mirror::String> string =
8282 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008283 if (string != nullptr) {
8284 dex_cache->SetResolvedString(string_idx, string);
8285 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008286 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008287}
8288
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008289ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008290 ObjPtr<mirror::Class> referrer) {
8291 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8292}
8293
8294ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008295 ObjPtr<mirror::DexCache> dex_cache,
8296 ObjPtr<mirror::ClassLoader> class_loader) {
8297 const DexFile& dex_file = *dex_cache->GetDexFile();
8298 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8299 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8300 ObjPtr<mirror::Class> type = nullptr;
8301 if (descriptor[1] == '\0') {
8302 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8303 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008304 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008305 } else {
8306 Thread* const self = Thread::Current();
8307 DCHECK(self != nullptr);
8308 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8309 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008310 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008311 }
8312 if (type != nullptr) {
8313 if (type->IsResolved()) {
8314 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008315 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008316 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008317 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008318 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008319 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008320}
8321
Andreas Gampe4835d212018-11-21 14:55:10 -08008322template <typename T>
8323ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, T referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008324 StackHandleScope<2> hs(Thread::Current());
8325 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8326 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8327 return DoResolveType(type_idx, dex_cache, class_loader);
8328}
8329
Andreas Gampe4835d212018-11-21 14:55:10 -08008330// Instantiate the above.
8331template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8332 ArtField* referrer);
8333template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8334 ArtMethod* referrer);
8335template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8336 ObjPtr<mirror::Class> referrer);
8337
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008338ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008339 Handle<mirror::DexCache> dex_cache,
8340 Handle<mirror::ClassLoader> class_loader) {
8341 Thread* self = Thread::Current();
8342 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8343 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8344 if (resolved != nullptr) {
8345 // TODO: we used to throw here if resolved's class loader was not the
8346 // boot class loader. This was to permit different classes with the
8347 // same name to be loaded simultaneously by different loaders
8348 dex_cache->SetResolvedType(type_idx, resolved);
8349 } else {
8350 CHECK(self->IsExceptionPending())
8351 << "Expected pending exception for failed resolution of: " << descriptor;
8352 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8353 StackHandleScope<1> hs(self);
8354 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008355 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008356 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8357 self->ClearException();
8358 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8359 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008360 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008361 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008362 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008363 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008364 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008365}
8366
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008367ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8368 ObjPtr<mirror::DexCache> dex_cache,
8369 ObjPtr<mirror::ClassLoader> class_loader,
8370 uint32_t method_idx) {
8371 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8372 // functions can optimize the search if the dex_cache is the same as the DexCache
8373 // of the class, with fall-back to name and signature search otherwise.
8374 ArtMethod* resolved = nullptr;
8375 if (klass->IsInterface()) {
8376 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8377 } else {
8378 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8379 }
8380 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008381 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008382 hiddenapi::ShouldDenyAccessToMember(resolved,
8383 hiddenapi::AccessContext(class_loader, dex_cache),
8384 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008385 resolved = nullptr;
8386 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008387 if (resolved != nullptr) {
8388 // In case of jmvti, the dex file gets verified before being registered, so first
8389 // check if it's registered before checking class tables.
8390 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008391 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8392 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008393 << "DexFile referrer: " << dex_file.GetLocation()
8394 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8395 // Be a good citizen and update the dex cache to speed subsequent calls.
8396 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008397 // Disable the following invariant check as the verifier breaks it. b/73760543
8398 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8399 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8400 // << "Method: " << resolved->PrettyMethod() << ", "
8401 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8402 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008403 }
8404 return resolved;
8405}
8406
David Brazdil4525e0b2018-04-05 16:57:32 +01008407// Returns true if `method` is either null or hidden.
8408// Does not print any warnings if it is hidden.
8409static bool CheckNoSuchMethod(ArtMethod* method,
8410 ObjPtr<mirror::DexCache> dex_cache,
8411 ObjPtr<mirror::ClassLoader> class_loader)
8412 REQUIRES_SHARED(Locks::mutator_lock_) {
8413 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008414 hiddenapi::ShouldDenyAccessToMember(method,
8415 hiddenapi::AccessContext(class_loader, dex_cache),
8416 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008417}
8418
8419ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8420 ObjPtr<mirror::DexCache> dex_cache,
8421 ObjPtr<mirror::ClassLoader> class_loader,
8422 uint32_t method_idx) {
8423 if (klass->IsInterface()) {
8424 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8425 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8426 } else {
8427 // If there was an interface method with the same signature, we would have
8428 // found it in the "copied" methods. Only DCHECK that the interface method
8429 // really does not exist.
8430 if (kIsDebugBuild) {
8431 ArtMethod* method =
8432 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8433 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8434 }
8435 return nullptr;
8436 }
8437}
8438
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008439template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008440ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008441 Handle<mirror::DexCache> dex_cache,
8442 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008443 ArtMethod* referrer,
8444 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008445 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008446 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008447 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008448 PointerSize pointer_size = image_pointer_size_;
8449 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008450 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008451 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8452 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008453 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8454 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008455 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008456 return resolved;
8457 }
Vladimir Marko89011192017-12-11 13:45:05 +00008458 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008459 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008460 ObjPtr<mirror::Class> klass = nullptr;
8461 if (valid_dex_cache_method) {
8462 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8463 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008464 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008465 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008466 // We normaly should not end up here. However the verifier currently doesn't guarantee
8467 // the invariant of having the klass in the class table. b/73760543
8468 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008469 }
Vladimir Markoba118822017-06-12 15:41:56 +01008470 } else {
8471 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008472 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008473 if (klass == nullptr) {
8474 DCHECK(Thread::Current()->IsExceptionPending());
8475 return nullptr;
8476 }
8477 }
8478
8479 // Check if the invoke type matches the class type.
8480 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008481 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008482 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008483 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008484 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008485 }
Vladimir Markoba118822017-06-12 15:41:56 +01008486
8487 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008488 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008489 }
Vladimir Markoba118822017-06-12 15:41:56 +01008490
8491 // Note: We can check for IllegalAccessError only if we have a referrer.
8492 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8493 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8494 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8495 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8496 resolved,
8497 dex_cache.Get(),
8498 method_idx,
8499 type)) {
8500 DCHECK(Thread::Current()->IsExceptionPending());
8501 return nullptr;
8502 }
8503 }
8504
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008505 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008506 if (LIKELY(resolved != nullptr) &&
8507 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8508 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008509 return resolved;
8510 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008511 // If we had a method, or if we can find one with another lookup type,
8512 // it's an incompatible-class-change error.
8513 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008514 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008515 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008516 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008517 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008518 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008519 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008520 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8521 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008522 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008523 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008524 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008525 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008526 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008527}
8528
Vladimir Marko89011192017-12-11 13:45:05 +00008529ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008530 Handle<mirror::DexCache> dex_cache,
8531 Handle<mirror::ClassLoader> class_loader) {
8532 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008533 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008534 if (resolved != nullptr) {
8535 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008536 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8537 return resolved;
8538 }
8539 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008540 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008541 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008542 if (klass == nullptr) {
8543 Thread::Current()->AssertPendingException();
8544 return nullptr;
8545 }
8546 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008547 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8548 } else {
8549 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008550 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008551 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008552 hiddenapi::ShouldDenyAccessToMember(
8553 resolved,
8554 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8555 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008556 resolved = nullptr;
8557 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008558 return resolved;
8559}
8560
Vladimir Markof44d36c2017-03-14 14:18:46 +00008561ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8562 ObjPtr<mirror::DexCache> dex_cache,
8563 ObjPtr<mirror::ClassLoader> class_loader,
8564 bool is_static) {
8565 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008566 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008567 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8568 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008569 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008570 }
8571 if (klass == nullptr) {
8572 // The class has not been resolved yet, so the field is also unresolved.
8573 return nullptr;
8574 }
8575 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008576
David Brazdil1ab0fa82018-05-04 11:28:03 +01008577 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008578}
8579
Vladimir Markoe11dd502017-12-08 14:09:45 +00008580ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008581 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008582 Handle<mirror::ClassLoader> class_loader,
8583 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008584 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008585 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008586 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008587 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008588 return resolved;
8589 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008590 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008591 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008592 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008593 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008594 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008595 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008596 }
8597
David Brazdil1ab0fa82018-05-04 11:28:03 +01008598 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008599 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008600 const char* name = dex_file.GetFieldName(field_id);
8601 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008602 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008603 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008604 return resolved;
8605}
8606
Vladimir Markoe11dd502017-12-08 14:09:45 +00008607ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008608 Handle<mirror::DexCache> dex_cache,
8609 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008610 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008611 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008612 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008613 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008614 return resolved;
8615 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008616 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008617 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008618 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008619 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008620 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008621 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008622 }
8623
David Brazdil1ab0fa82018-05-04 11:28:03 +01008624 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
8625 if (resolved == nullptr) {
8626 const char* name = dex_file.GetFieldName(field_id);
8627 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008628 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008629 }
8630 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008631}
8632
David Brazdil1ab0fa82018-05-04 11:28:03 +01008633ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
8634 ObjPtr<mirror::DexCache> dex_cache,
8635 ObjPtr<mirror::ClassLoader> class_loader,
8636 uint32_t field_idx,
8637 bool is_static) {
8638 ArtField* resolved = nullptr;
8639 Thread* self = is_static ? Thread::Current() : nullptr;
8640 const DexFile& dex_file = *dex_cache->GetDexFile();
8641
8642 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8643 : klass->FindInstanceField(dex_cache, field_idx);
8644
8645 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008646 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008647 const char* name = dex_file.GetFieldName(field_id);
8648 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8649 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
8650 : klass->FindInstanceField(name, type);
8651 }
8652
8653 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008654 hiddenapi::ShouldDenyAccessToMember(resolved,
8655 hiddenapi::AccessContext(class_loader, dex_cache),
8656 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008657 resolved = nullptr;
8658 }
8659
8660 if (resolved != nullptr) {
8661 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8662 }
8663
8664 return resolved;
8665}
8666
8667ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
8668 ObjPtr<mirror::DexCache> dex_cache,
8669 ObjPtr<mirror::ClassLoader> class_loader,
8670 uint32_t field_idx) {
8671 ArtField* resolved = nullptr;
8672 Thread* self = Thread::Current();
8673 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008674 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008675
8676 const char* name = dex_file.GetFieldName(field_id);
8677 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8678 resolved = mirror::Class::FindField(self, klass, name, type);
8679
8680 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008681 hiddenapi::ShouldDenyAccessToMember(resolved,
8682 hiddenapi::AccessContext(class_loader, dex_cache),
8683 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008684 resolved = nullptr;
8685 }
8686
8687 if (resolved != nullptr) {
8688 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8689 }
8690
8691 return resolved;
8692}
8693
Vladimir Markoaf940202017-12-08 15:01:18 +00008694ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8695 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008696 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008697 Handle<mirror::DexCache> dex_cache,
8698 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008699 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008700 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008701
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008702 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008703 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01008704 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01008705 }
8706
Narayan Kamath25352fc2016-08-03 12:46:58 +01008707 StackHandleScope<4> hs(self);
8708
8709 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008710 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008711 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008712 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008713 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008714 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008715 DCHECK(self->IsExceptionPending());
8716 return nullptr;
8717 }
8718
8719 // Then resolve the argument types.
8720 //
8721 // TODO: Is there a better way to figure out the number of method arguments
8722 // other than by looking at the shorty ?
8723 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8724
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008725 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008726 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8727 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008728 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008729 DCHECK(self->IsExceptionPending());
8730 return nullptr;
8731 }
8732
8733 DexFileParameterIterator it(dex_file, proto_id);
8734 int32_t i = 0;
8735 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8736 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008737 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008738 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008739 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008740 DCHECK(self->IsExceptionPending());
8741 return nullptr;
8742 }
8743
8744 method_params->Set(i++, param_class.Get());
8745 }
8746
8747 DCHECK(!it.HasNext());
8748
8749 Handle<mirror::MethodType> type = hs.NewHandle(
8750 mirror::MethodType::Create(self, return_type, method_params));
8751 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8752
8753 return type.Get();
8754}
8755
Vladimir Markoaf940202017-12-08 15:01:18 +00008756ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008757 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008758 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008759 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008760 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8761 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008762 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008763}
8764
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008765mirror::MethodHandle* ClassLinker::ResolveMethodHandleForField(
8766 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008767 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008768 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008769 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008770 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8771 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008772 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008773 bool is_static;
8774 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008775 switch (handle_type) {
8776 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008777 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008778 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008779 is_static = true;
8780 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008781 break;
8782 }
8783 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008784 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008785 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008786 is_static = true;
8787 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008788 break;
8789 }
8790 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008791 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008792 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008793 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008794 num_params = 2;
8795 break;
8796 }
8797 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008798 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008799 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008800 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008801 num_params = 1;
8802 break;
8803 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008804 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008805 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008806 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008807 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008808 case DexFile::MethodHandleType::kInvokeInterface:
8809 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008810 }
8811
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008812 ArtField* target_field =
8813 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8814 if (LIKELY(target_field != nullptr)) {
8815 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8816 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8817 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8818 ThrowIllegalAccessErrorField(referring_class, target_field);
8819 return nullptr;
8820 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008821 if (UNLIKELY(is_put && target_field->IsFinal())) {
8822 ThrowIllegalAccessErrorField(referring_class, target_field);
8823 return nullptr;
8824 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008825 } else {
8826 DCHECK(Thread::Current()->IsExceptionPending());
8827 return nullptr;
8828 }
8829
8830 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008831 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00008832 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8833 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008834 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008835 DCHECK(self->IsExceptionPending());
8836 return nullptr;
8837 }
8838
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008839 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008840 Handle<mirror::Class> return_type;
8841 switch (handle_type) {
8842 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008843 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008844 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008845 break;
8846 }
8847 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008848 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008849 break;
8850 }
8851 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008852 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008853 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008854 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008855 break;
8856 }
8857 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008858 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008859 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008860 break;
8861 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008862 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008863 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008864 case DexFile::MethodHandleType::kInvokeConstructor:
8865 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008866 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008867 UNREACHABLE();
8868 }
8869
8870 for (int32_t i = 0; i < num_params; ++i) {
8871 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8872 DCHECK(self->IsExceptionPending());
8873 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00008874 }
8875 }
8876
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008877 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008878 DCHECK(self->IsExceptionPending());
8879 return nullptr;
8880 }
8881
8882 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008883 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
8884 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008885 DCHECK(self->IsExceptionPending());
8886 return nullptr;
8887 }
Orion Hodson631827d2017-04-10 14:53:47 +01008888
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008889 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
8890 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
8891}
8892
8893mirror::MethodHandle* ClassLinker::ResolveMethodHandleForMethod(
8894 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008895 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008896 ArtMethod* referrer) {
8897 DexFile::MethodHandleType handle_type =
8898 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8899 mirror::MethodHandle::Kind kind;
8900 uint32_t receiver_count = 0;
8901 ArtMethod* target_method = nullptr;
8902 switch (handle_type) {
8903 case DexFile::MethodHandleType::kStaticPut:
8904 case DexFile::MethodHandleType::kStaticGet:
8905 case DexFile::MethodHandleType::kInstancePut:
8906 case DexFile::MethodHandleType::kInstanceGet:
8907 UNREACHABLE();
8908 case DexFile::MethodHandleType::kInvokeStatic: {
8909 kind = mirror::MethodHandle::Kind::kInvokeStatic;
8910 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008911 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8912 method_handle.field_or_method_idx_,
8913 referrer,
8914 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008915 break;
8916 }
8917 case DexFile::MethodHandleType::kInvokeInstance: {
8918 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
8919 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008920 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8921 method_handle.field_or_method_idx_,
8922 referrer,
8923 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008924 break;
8925 }
8926 case DexFile::MethodHandleType::kInvokeConstructor: {
8927 // Constructors are currently implemented as a transform. They
8928 // are special cased later in this method.
8929 kind = mirror::MethodHandle::Kind::kInvokeTransform;
8930 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01008931 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8932 method_handle.field_or_method_idx_,
8933 referrer,
8934 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008935 break;
8936 }
8937 case DexFile::MethodHandleType::kInvokeDirect: {
8938 kind = mirror::MethodHandle::Kind::kInvokeDirect;
8939 receiver_count = 1;
8940 StackHandleScope<2> hs(self);
8941 // A constant method handle with type kInvokeDirect can refer to
8942 // a method that is private or to a method in a super class. To
8943 // disambiguate the two options, we resolve the method ignoring
8944 // the invocation type to determine if the method is private. We
8945 // then resolve again specifying the intended invocation type to
8946 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00008947 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008948 hs.NewHandle(referrer->GetDexCache()),
8949 hs.NewHandle(referrer->GetClassLoader()));
8950 if (UNLIKELY(target_method == nullptr)) {
8951 break;
8952 }
8953
8954 if (target_method->IsPrivate()) {
8955 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01008956 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8957 method_handle.field_or_method_idx_,
8958 referrer,
8959 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008960 } else {
8961 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01008962 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8963 method_handle.field_or_method_idx_,
8964 referrer,
8965 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008966 if (UNLIKELY(target_method == nullptr)) {
8967 break;
8968 }
8969 // Find the method specified in the parent in referring class
8970 // so invoke-super invokes the method in the parent of the
8971 // referrer.
8972 target_method =
8973 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
8974 kRuntimePointerSize);
8975 }
8976 break;
8977 }
8978 case DexFile::MethodHandleType::kInvokeInterface: {
8979 kind = mirror::MethodHandle::Kind::kInvokeInterface;
8980 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01008981 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
8982 method_handle.field_or_method_idx_,
8983 referrer,
8984 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008985 break;
8986 }
Orion Hodson631827d2017-04-10 14:53:47 +01008987 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008988
8989 if (UNLIKELY(target_method == nullptr)) {
8990 DCHECK(Thread::Current()->IsExceptionPending());
8991 return nullptr;
8992 }
8993
8994 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
8995 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8996 uint32_t access_flags = target_method->GetAccessFlags();
8997 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
8998 ThrowIllegalAccessErrorMethod(referring_class, target_method);
8999 return nullptr;
9000 }
9001
9002 // Calculate the number of parameters from the method shorty. We add the
9003 // receiver count (0 or 1) and deduct one for the return value.
9004 uint32_t shorty_length;
9005 target_method->GetShorty(&shorty_length);
9006 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9007
Orion Hodsonecd58562018-09-24 11:27:33 +01009008 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009009 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009010 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9011 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9012 if (method_params.Get() == nullptr) {
9013 DCHECK(self->IsExceptionPending());
9014 return nullptr;
9015 }
9016
Orion Hodsonecd58562018-09-24 11:27:33 +01009017 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009018 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009019 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009020 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009021 // Insert receiver. Use the class identified in the method handle rather than the declaring
9022 // class of the resolved method which may be super class or default interface method
9023 // (b/115964401).
9024 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9025 // receiver_class should have been resolved when resolving the target method.
9026 DCHECK(receiver_class != nullptr);
9027 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009028 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009029
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009030 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009031 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009032 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009033 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009034 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009035 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009036 if (nullptr == klass) {
9037 DCHECK(self->IsExceptionPending());
9038 return nullptr;
9039 }
9040 method_params->Set(index++, klass);
9041 it.Next();
9042 }
9043
Orion Hodsonecd58562018-09-24 11:27:33 +01009044 Handle<mirror::Class> return_type =
9045 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009046 if (UNLIKELY(return_type.IsNull())) {
9047 DCHECK(self->IsExceptionPending());
9048 return nullptr;
9049 }
9050
9051 Handle<mirror::MethodType>
9052 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9053 if (UNLIKELY(method_type.IsNull())) {
9054 DCHECK(self->IsExceptionPending());
9055 return nullptr;
9056 }
9057
9058 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9059 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9060 Handle<mirror::MethodHandlesLookup> lookup =
9061 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9062 return lookup->FindConstructor(self, constructor_class, method_type);
9063 }
9064
9065 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9066 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9067}
9068
Vladimir Markoaf940202017-12-08 15:01:18 +00009069ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9070 uint32_t method_handle_idx,
9071 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009072 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009073 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009074 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009075 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9076 case DexFile::MethodHandleType::kStaticPut:
9077 case DexFile::MethodHandleType::kStaticGet:
9078 case DexFile::MethodHandleType::kInstancePut:
9079 case DexFile::MethodHandleType::kInstanceGet:
9080 return ResolveMethodHandleForField(self, method_handle, referrer);
9081 case DexFile::MethodHandleType::kInvokeStatic:
9082 case DexFile::MethodHandleType::kInvokeInstance:
9083 case DexFile::MethodHandleType::kInvokeConstructor:
9084 case DexFile::MethodHandleType::kInvokeDirect:
9085 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009086 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009087 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009088}
9089
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009090bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9091 return (entry_point == GetQuickResolutionStub()) ||
9092 (quick_resolution_trampoline_ == entry_point);
9093}
9094
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009095bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9096 return (entry_point == GetQuickToInterpreterBridge()) ||
9097 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9098}
9099
9100bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9101 return (entry_point == GetQuickGenericJniStub()) ||
9102 (quick_generic_jni_trampoline_ == entry_point);
9103}
9104
David Sehra49e0532017-08-25 08:05:29 -07009105bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
9106 return entry_point == GetJniDlsymLookupStub();
9107}
9108
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009109const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9110 return GetQuickGenericJniStub();
9111}
9112
Mathieu Chartiere401d142015-04-22 13:56:20 -07009113void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009114 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009115 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9116 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009117 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009118 }
9119}
9120
Alex Lightdb01a092017-04-03 15:39:55 -07009121void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9122 DCHECK(method->IsObsolete());
9123 // We cannot mess with the entrypoints of native methods because they are used to determine how
9124 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9125 if (!method->IsNative()) {
9126 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9127 }
9128}
9129
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009130void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009131 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009132 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009133 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9134 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009135 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9136 os << "Dumping registered class loaders\n";
9137 size_t class_loader_index = 0;
9138 for (const ClassLoaderData& class_loader : class_loaders_) {
9139 ObjPtr<mirror::ClassLoader> loader =
9140 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9141 if (loader != nullptr) {
9142 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9143 bool saw_one_dex_file = false;
9144 for (const DexCacheData& dex_cache : dex_caches_) {
9145 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9146 if (saw_one_dex_file) {
9147 os << ":";
9148 }
9149 saw_one_dex_file = true;
9150 os << dex_cache.dex_file->GetLocation();
9151 }
9152 }
9153 os << "]";
9154 bool found_parent = false;
9155 if (loader->GetParent() != nullptr) {
9156 size_t parent_index = 0;
9157 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9158 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9159 soa.Self()->DecodeJObject(class_loader2.weak_root));
9160 if (loader2 == loader->GetParent()) {
9161 os << ", parent #" << parent_index;
9162 found_parent = true;
9163 break;
9164 }
9165 parent_index++;
9166 }
9167 if (!found_parent) {
9168 os << ", unregistered parent of type "
9169 << loader->GetParent()->GetClass()->PrettyDescriptor();
9170 }
9171 } else {
9172 os << ", no parent";
9173 }
9174 os << "\n";
9175 }
9176 }
9177 os << "Done dumping class loaders\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009178}
9179
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009180class CountClassesVisitor : public ClassLoaderVisitor {
9181 public:
9182 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9183
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009184 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009185 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009186 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009187 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009188 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9189 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009190 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009191 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009192
9193 size_t num_zygote_classes;
9194 size_t num_non_zygote_classes;
9195};
9196
9197size_t ClassLinker::NumZygoteClasses() const {
9198 CountClassesVisitor visitor;
9199 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009200 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009201}
9202
9203size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009204 CountClassesVisitor visitor;
9205 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009206 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009207}
9208
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009209size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009210 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009211 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009212 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009213}
9214
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009215pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009216 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009217}
9218
9219pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009220 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009221}
9222
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009223void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009224 DCHECK(!init_done_);
9225
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009226 DCHECK(klass != nullptr);
9227 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009228
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009229 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009230 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009231 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9232 int32_t index = static_cast<int32_t>(class_root);
9233 DCHECK(class_roots->Get(index) == nullptr);
9234 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009235}
9236
Roland Levillain0e840272018-08-23 19:55:30 +01009237void ClassLinker::AllocAndSetPrimitiveArrayClassRoot(Thread* self,
9238 ObjPtr<mirror::Class> java_lang_Class,
9239 ClassRoot primitive_array_class_root,
9240 ClassRoot primitive_class_root,
9241 const char* descriptor) {
9242 StackHandleScope<1> hs(self);
9243 Handle<mirror::Class> primitive_array_class(hs.NewHandle(
9244 AllocPrimitiveArrayClass(self, java_lang_Class)));
9245 primitive_array_class->SetComponentType(GetClassRoot(primitive_class_root, this));
9246 SetClassRoot(primitive_array_class_root, primitive_array_class.Get());
9247 CheckSystemClass(self, primitive_array_class, descriptor);
9248}
9249
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009250ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9251 Thread* self,
9252 const std::vector<const DexFile*>& dex_files,
9253 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009254 Handle<mirror::ClassLoader> parent_loader,
9255 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009256
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009257 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009258
Mathieu Chartierc7853442015-03-27 14:35:38 -07009259 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009260 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009261
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009262 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009263 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009264 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009265 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009266 mirror::ObjectArray<mirror::Object>::Alloc(self,
9267 dex_elements_class.Get(),
9268 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009269 Handle<mirror::Class> h_dex_element_class =
9270 hs.NewHandle(dex_elements_class->GetComponentType());
9271
Mathieu Chartierc7853442015-03-27 14:35:38 -07009272 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009273 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009274 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009275
Andreas Gampe08883de2016-11-08 13:20:52 -08009276 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009277 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009278
Andreas Gampe08883de2016-11-08 13:20:52 -08009279 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009280 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009281
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009282 // Fill the elements array.
9283 int32_t index = 0;
9284 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009285 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009286
Calin Juravle7865ac72017-06-28 11:03:12 -07009287 // CreateWellKnownClassLoader is only used by gtests and compiler.
9288 // Index 0 of h_long_array is supposed to be the oat file but we can leave it null.
Mathieu Chartiere58991b2015-10-13 07:59:34 -07009289 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9290 self,
9291 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009292 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009293 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009294
Mathieu Chartier3738e982017-05-12 16:07:28 -07009295 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9296 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009297 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009298 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009299 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009300 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009301
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009302 Handle<mirror::String> h_file_name = hs2.NewHandle(
9303 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009304 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009305 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9306
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009307 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009308 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009309 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009310
9311 h_dex_elements->Set(index, h_element.Get());
9312 index++;
9313 }
9314 DCHECK_EQ(index, h_dex_elements->GetLength());
9315
9316 // Create DexPathList.
9317 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009318 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009319 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009320 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009321 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009322 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9323 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9324 // elements.
9325 {
9326 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9327 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9328 DCHECK(native_lib_dirs != nullptr);
9329 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9330 DCHECK(list_class != nullptr);
9331 {
9332 StackHandleScope<1> h_list_scope(self);
9333 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9334 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9335 DCHECK(list_init);
9336 list_class = h_list_class.Get();
9337 }
9338 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9339 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9340 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9341 // normally never null), as long as one does not try to add elements, this will still
9342 // work.
9343 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9344 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009345
Calin Juravle7865ac72017-06-28 11:03:12 -07009346 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009347 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9348 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009349 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009350 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009351 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009352 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009353 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009354 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009355
9356 // Make a pretend boot-classpath.
9357 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009358 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009359 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009360 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009361 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009362 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009363 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009364 if (parent_loader.Get() == nullptr) {
9365 ScopedObjectAccessUnchecked soa(self);
9366 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9367 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9368 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9369 } else {
9370 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9371 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009372
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009373 ArtField* shared_libraries_field =
9374 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9375 DCHECK(shared_libraries_field != nullptr);
9376 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9377
9378 return h_class_loader.Get();
9379}
9380
9381jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9382 const std::vector<const DexFile*>& dex_files,
9383 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009384 jobject parent_loader,
9385 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009386 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9387 WellKnownClasses::dalvik_system_PathClassLoader) ||
9388 self->GetJniEnv()->IsSameObject(loader_class,
9389 WellKnownClasses::dalvik_system_DelegateLastClassLoader));
9390
9391 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9392 // We could move the jobject to the callers, but all call-sites do this...
9393 ScopedObjectAccessUnchecked soa(self);
9394
9395 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009396 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009397
9398 Handle<mirror::Class> h_loader_class =
9399 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009400 Handle<mirror::ClassLoader> h_parent =
9401 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9402 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9403 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009404
9405 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9406 self,
9407 dex_files,
9408 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009409 h_parent,
9410 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009411
9412 // Make it a global ref and return.
9413 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009414 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009415 return soa.Env()->NewGlobalRef(local_ref.get());
9416}
9417
Calin Juravle7865ac72017-06-28 11:03:12 -07009418jobject ClassLinker::CreatePathClassLoader(Thread* self,
9419 const std::vector<const DexFile*>& dex_files) {
9420 return CreateWellKnownClassLoader(self,
9421 dex_files,
9422 WellKnownClasses::dalvik_system_PathClassLoader,
9423 nullptr);
9424}
9425
Andreas Gampe8ac75952015-06-02 21:01:45 -07009426void ClassLinker::DropFindArrayClassCache() {
9427 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9428 find_array_class_cache_next_victim_ = 0;
9429}
9430
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009431void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009432 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009433 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009434 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009435 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9436 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009437 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009438 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009439 }
9440 }
9441}
9442
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009443void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9444 for (const ClassLoaderData& data : class_loaders_) {
9445 LinearAlloc* alloc = data.allocator;
9446 if (alloc != nullptr && !visitor->Visit(alloc)) {
9447 break;
9448 }
9449 }
9450}
9451
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009452void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9453 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009454 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009455 Thread* const self = Thread::Current();
9456 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009457 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009458 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009459 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009460 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9461 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009462 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009463 }
9464}
9465
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009466void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009467 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009468 std::vector<ClassLoaderData> to_delete;
9469 // Do the delete outside the lock to avoid lock violation in jit code cache.
9470 {
9471 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9472 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9473 const ClassLoaderData& data = *it;
9474 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009475 ObjPtr<mirror::ClassLoader> class_loader =
9476 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009477 if (class_loader != nullptr) {
9478 ++it;
9479 } else {
9480 VLOG(class_linker) << "Freeing class loader";
9481 to_delete.push_back(data);
9482 it = class_loaders_.erase(it);
9483 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009484 }
9485 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009486 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009487 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009488 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009489 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009490}
9491
Vladimir Marko21300532017-01-24 18:06:55 +00009492class GetResolvedClassesVisitor : public ClassVisitor {
9493 public:
9494 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
9495 : result_(result),
9496 ignore_boot_classes_(ignore_boot_classes),
9497 last_resolved_classes_(result->end()),
9498 last_dex_file_(nullptr),
9499 vlog_is_on_(VLOG_IS_ON(class_linker)),
9500 extra_stats_(),
9501 last_extra_stats_(extra_stats_.end()) { }
9502
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009503 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko21300532017-01-24 18:06:55 +00009504 if (!klass->IsProxyClass() &&
9505 !klass->IsArrayClass() &&
9506 klass->IsResolved() &&
9507 !klass->IsErroneousResolved() &&
9508 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
9509 const DexFile& dex_file = klass->GetDexFile();
9510 if (&dex_file != last_dex_file_) {
9511 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07009512 DexCacheResolvedClasses resolved_classes(
9513 dex_file.GetLocation(),
9514 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
9515 dex_file.GetLocationChecksum(),
9516 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00009517 last_resolved_classes_ = result_->find(resolved_classes);
9518 if (last_resolved_classes_ == result_->end()) {
9519 last_resolved_classes_ = result_->insert(resolved_classes).first;
9520 }
9521 }
9522 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
9523 if (UNLIKELY(vlog_is_on_) && added) {
9524 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
9525 if (last_extra_stats_ == extra_stats_.end() ||
9526 last_extra_stats_->first != resolved_classes) {
9527 last_extra_stats_ = extra_stats_.find(resolved_classes);
9528 if (last_extra_stats_ == extra_stats_.end()) {
9529 last_extra_stats_ =
9530 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
9531 }
9532 }
9533 }
9534 }
9535 return true;
9536 }
9537
9538 void PrintStatistics() const {
9539 if (vlog_is_on_) {
9540 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
9541 auto it = extra_stats_.find(std::addressof(resolved_classes));
9542 DCHECK(it != extra_stats_.end());
9543 const ExtraStats& extra_stats = it->second;
9544 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
9545 << " has " << resolved_classes.GetClasses().size() << " / "
9546 << extra_stats.number_of_class_defs_ << " resolved classes";
9547 }
9548 }
9549 }
9550
9551 private:
9552 struct ExtraStats {
9553 explicit ExtraStats(uint32_t number_of_class_defs)
9554 : number_of_class_defs_(number_of_class_defs) {}
9555 uint32_t number_of_class_defs_;
9556 };
9557
9558 std::set<DexCacheResolvedClasses>* result_;
9559 bool ignore_boot_classes_;
9560 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
9561 const DexFile* last_dex_file_;
9562
9563 // Statistics.
9564 bool vlog_is_on_;
9565 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
9566 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
9567};
9568
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009569std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08009570 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009571 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07009572 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009573 std::set<DexCacheResolvedClasses> ret;
9574 VLOG(class_linker) << "Collecting resolved classes";
9575 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00009576 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
9577 VisitClasses(&visitor);
9578 if (VLOG_IS_ON(class_linker)) {
9579 visitor.PrintStatistics();
9580 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009581 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009582 return ret;
9583}
9584
Mathieu Chartier65975772016-08-05 10:46:36 -07009585class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9586 public:
9587 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9588 : method_(method),
9589 pointer_size_(pointer_size) {}
9590
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009591 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009592 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9593 holder_ = klass;
9594 }
9595 // Return false to stop searching if holder_ is not null.
9596 return holder_ == nullptr;
9597 }
9598
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009599 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009600 const ArtMethod* const method_;
9601 const PointerSize pointer_size_;
9602};
9603
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009604ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -07009605 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9606 CHECK(method->IsCopied());
9607 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9608 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009609 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -07009610}
9611
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009612ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9613 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009614 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009615 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009616 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009617}
9618
Roland Levillain0e840272018-08-23 19:55:30 +01009619// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009620template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009621 uint32_t method_idx,
9622 Handle<mirror::DexCache> dex_cache,
9623 Handle<mirror::ClassLoader> class_loader,
9624 ArtMethod* referrer,
9625 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009626template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009627 uint32_t method_idx,
9628 Handle<mirror::DexCache> dex_cache,
9629 Handle<mirror::ClassLoader> class_loader,
9630 ArtMethod* referrer,
9631 InvokeType type);
9632
Roland Levillain0e840272018-08-23 19:55:30 +01009633// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009634template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +01009635 Thread* self,
9636 ObjPtr<mirror::Class> java_lang_Class,
9637 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009638template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01009639 Thread* self,
9640 ObjPtr<mirror::Class> java_lang_Class,
9641 uint32_t class_size);
9642
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009643} // namespace art