blob: f123246ebde8cb172ea66e55a6f5446e60aef8bc [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"
Vladimir Markob9c29f62019-03-20 14:22:51 +000047#include "base/string_view_cpp20.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080048#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010049#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080050#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080051#include "base/utils.h"
Andreas Gampeb9aec2c2015-04-23 22:23:47 -070052#include "base/value_object.h"
Mingyao Yang063fc772016-08-02 11:02:54 -070053#include "cha.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080054#include "class_linker-inl.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070055#include "class_loader_utils.h"
Vladimir Markob4eb1b12018-05-24 11:09:38 +010056#include "class_root.h"
Mathieu Chartiere4275c02015-08-06 15:34:15 -070057#include "class_table-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000058#include "compiler_callbacks.h"
Vladimir Marko606adb32018-04-05 14:49:24 +010059#include "debug_print.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080060#include "debugger.h"
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -070061#include "dex/class_accessor-inl.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080062#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080063#include "dex/dex_file-inl.h"
64#include "dex/dex_file_exception_helpers.h"
65#include "dex/dex_file_loader.h"
Andreas Gampead1aa632019-01-02 10:30:54 -080066#include "dex/signature-inl.h"
David Sehr0225f8e2018-01-31 08:52:24 +000067#include "dex/utf.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070068#include "entrypoints/entrypoint_utils.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070069#include "entrypoints/runtime_asm_entrypoints.h"
Alex Light705ad492015-09-21 11:36:30 -070070#include "experimental_flags.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070071#include "gc/accounting/card_table-inl.h"
Mathieu Chartier03c1dd92016-03-07 16:13:54 -080072#include "gc/accounting/heap_bitmap-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +000073#include "gc/accounting/space_bitmap-inl.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070074#include "gc/heap-visit-objects-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070075#include "gc/heap.h"
Mathieu Chartier1b1e31f2016-05-19 10:13:04 -070076#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070077#include "gc/space/image_space.h"
Vladimir Marko8d6768d2017-03-14 10:13:21 +000078#include "gc/space/space-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070079#include "gc_root-inl.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -070080#include "handle_scope-inl.h"
Andreas Gampeaa120012018-03-28 16:23:24 -070081#include "hidden_api.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080082#include "image-inl.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070083#include "imt_conflict_table.h"
84#include "imtable-inl.h"
Mathieu Chartier74ccee62018-10-10 10:30:29 -070085#include "intern_table-inl.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070086#include "interpreter/interpreter.h"
David Srbeckyfb3de3d2018-01-29 16:11:49 +000087#include "jit/debugger_interface.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080088#include "jit/jit.h"
89#include "jit/jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010090#include "jni/java_vm_ext.h"
91#include "jni/jni_internal.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070092#include "linear_alloc.h"
Andreas Gampe8e0f0432018-10-24 13:38:03 -070093#include "mirror/array-alloc-inl.h"
94#include "mirror/array-inl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +000095#include "mirror/call_site.h"
Andreas Gampe70f5fd02018-10-24 19:58:37 -070096#include "mirror/class-alloc-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080097#include "mirror/class-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070098#include "mirror/class.h"
Alex Lightd6251582016-10-31 11:12:30 -070099#include "mirror/class_ext.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800100#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -0700101#include "mirror/dex_cache-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700102#include "mirror/dex_cache.h"
Narayan Kamath000e1882016-10-24 17:14:25 +0100103#include "mirror/emulated_stack_frame.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700104#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800105#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700106#include "mirror/method.h"
Narayan Kamathafa48272016-08-03 12:46:58 +0100107#include "mirror/method_handle_impl.h"
Orion Hodsonc069a302017-01-18 09:23:12 +0000108#include "mirror/method_handles_lookup.h"
Steven Morelande431e272017-07-18 16:53:49 -0700109#include "mirror/method_type.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800110#include "mirror/object-inl.h"
Chang Xingba17dbd2017-06-28 21:27:56 +0000111#include "mirror/object-refvisitor-inl.h"
Andreas Gampe52ecb652018-10-24 15:18:21 -0700112#include "mirror/object_array-alloc-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700113#include "mirror/object_array-inl.h"
Chris Wailes0c61be42018-09-26 17:27:34 -0700114#include "mirror/object_reference.h"
115#include "mirror/object_reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800116#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -0700117#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800118#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700119#include "mirror/string-inl.h"
Andreas Gampe501c3b02019-04-17 21:54:27 +0000120#include "mirror/throwable.h"
Orion Hodson005ac512017-10-24 15:43:43 +0100121#include "mirror/var_handle.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700122#include "native/dalvik_system_DexFile.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -0700123#include "nativehelper/scoped_local_ref.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700124#include "oat.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700125#include "oat_file-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700126#include "oat_file.h"
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700127#include "oat_file_assistant.h"
128#include "oat_file_manager.h"
129#include "object_lock.h"
David Sehr82d046e2018-04-23 08:14:19 -0700130#include "profile/profile_compilation_info.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -0700131#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800132#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700133#include "scoped_thread_state_change-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -0700134#include "thread-inl.h"
Mingyao Yang063fc772016-08-02 11:02:54 -0700135#include "thread_list.h"
Mathieu Chartier7778b882015-10-05 16:41:10 -0700136#include "trace.h"
Vladimir Marko05792b92015-08-03 11:56:49 +0100137#include "utils/dex_cache_arrays_layout-inl.h"
Andreas Gampea43ba3d2019-03-13 15:49:20 -0700138#include "verifier/class_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700139#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700140
141namespace art {
142
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800143using android::base::StringPrintf;
144
Mathieu Chartierc7853442015-03-27 14:35:38 -0700145static constexpr bool kSanityCheckObjects = kIsDebugBuild;
Mathieu Chartier8790c7f2016-03-31 15:05:45 -0700146static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700147
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700148static void ThrowNoClassDefFoundError(const char* fmt, ...)
149 __attribute__((__format__(__printf__, 1, 2)))
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700150 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -0700151static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700152 va_list args;
153 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800154 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000155 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -0800156 va_end(args);
157}
158
Andreas Gampe99babb62015-11-02 16:20:00 -0800159static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700160 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700161 ArtMethod* method = self->GetCurrentMethod(nullptr);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700162 StackHandleScope<1> hs(self);
163 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
Mathieu Chartier90443472015-07-16 20:32:27 -0700164 method->GetDeclaringClass()->GetClassLoader() : nullptr));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700165 ObjPtr<mirror::Class> exception_class = class_linker->FindClass(self, descriptor, class_loader);
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700166
167 if (exception_class == nullptr) {
168 // No exc class ~ no <init>-with-string.
169 CHECK(self->IsExceptionPending());
170 self->ClearException();
171 return false;
172 }
173
Vladimir Markoba118822017-06-12 15:41:56 +0100174 ArtMethod* exception_init_method = exception_class->FindConstructor(
175 "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700176 return exception_init_method != nullptr;
177}
178
Vladimir Markobb206de2019-03-28 10:30:32 +0000179static ObjPtr<mirror::Object> GetVerifyError(ObjPtr<mirror::Class> c)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700180 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lightd6251582016-10-31 11:12:30 -0700181 ObjPtr<mirror::ClassExt> ext(c->GetExtData());
182 if (ext == nullptr) {
183 return nullptr;
184 } else {
185 return ext->GetVerifyError();
186 }
187}
188
189// Helper for ThrowEarlierClassFailure. Throws the stored error.
190static void HandleEarlierVerifyError(Thread* self,
191 ClassLinker* class_linker,
192 ObjPtr<mirror::Class> c)
193 REQUIRES_SHARED(Locks::mutator_lock_) {
194 ObjPtr<mirror::Object> obj = GetVerifyError(c);
Andreas Gampe99babb62015-11-02 16:20:00 -0800195 DCHECK(obj != nullptr);
196 self->AssertNoPendingException();
197 if (obj->IsClass()) {
198 // Previous error has been stored as class. Create a new exception of that type.
199
200 // It's possible the exception doesn't have a <init>(String).
201 std::string temp;
202 const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
203
204 if (HasInitWithString(self, class_linker, descriptor)) {
David Sehr709b0702016-10-13 09:12:37 -0700205 self->ThrowNewException(descriptor, c->PrettyDescriptor().c_str());
Andreas Gampe99babb62015-11-02 16:20:00 -0800206 } else {
207 self->ThrowNewException(descriptor, nullptr);
208 }
209 } else {
210 // Previous error has been stored as an instance. Just rethrow.
Vladimir Markoc13fbd82018-06-04 16:16:28 +0100211 ObjPtr<mirror::Class> throwable_class = GetClassRoot<mirror::Throwable>(class_linker);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700212 ObjPtr<mirror::Class> error_class = obj->GetClass();
Andreas Gampe99babb62015-11-02 16:20:00 -0800213 CHECK(throwable_class->IsAssignableFrom(error_class));
214 self->SetException(obj->AsThrowable());
215 }
216 self->AssertPendingException();
217}
218
Andreas Gampe5b20b352018-10-11 19:03:20 -0700219// Ensures that methods have the kAccSkipAccessChecks bit set. We use the
220// kAccVerificationAttempted bit on the class access flags to determine whether this has been done
221// before.
222template <bool kNeedsVerified = false>
223static void EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass, PointerSize pointer_size)
224 REQUIRES_SHARED(Locks::mutator_lock_) {
225 if (kNeedsVerified) {
226 // To not fail access-flags access checks, push a minimal state.
227 mirror::Class::SetStatus(klass, ClassStatus::kVerified, Thread::Current());
228 }
229 if (!klass->WasVerificationAttempted()) {
230 klass->SetSkipAccessChecksFlagOnAllMethods(pointer_size);
231 klass->SetVerificationAttempted();
232 }
233}
234
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800235void ClassLinker::ThrowEarlierClassFailure(ObjPtr<mirror::Class> c,
236 bool wrap_in_no_class_def,
237 bool log) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700238 // The class failed to initialize on a previous attempt, so we want to throw
239 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
240 // failed in verification, in which case v2 5.4.1 says we need to re-throw
241 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800242 Runtime* const runtime = Runtime::Current();
243 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700244 std::string extra;
Vladimir Markobb206de2019-03-28 10:30:32 +0000245 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
246 if (verify_error != nullptr) {
Andreas Gampe369c8512016-01-28 15:31:39 -0800247 if (verify_error->IsClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700248 extra = mirror::Class::PrettyDescriptor(verify_error->AsClass());
Andreas Gampe369c8512016-01-28 15:31:39 -0800249 } else {
250 extra = verify_error->AsThrowable()->Dump();
251 }
Andreas Gampe3d6b4702015-09-21 08:35:52 -0700252 }
Andreas Gampe7b3063b2019-01-07 14:12:52 -0800253 if (log) {
254 LOG(INFO) << "Rejecting re-init on previously-failed class " << c->PrettyClass()
255 << ": " << extra;
256 }
Ian Rogers87e552d2012-08-31 15:54:48 -0700257 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700258
David Sehr709b0702016-10-13 09:12:37 -0700259 CHECK(c->IsErroneous()) << c->PrettyClass() << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800260 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800261 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700262 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700263 ObjPtr<mirror::Throwable> pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000264 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700265 } else {
Vladimir Markobb206de2019-03-28 10:30:32 +0000266 ObjPtr<mirror::Object> verify_error = GetVerifyError(c);
267 if (verify_error != nullptr) {
Andreas Gampecb086952015-11-02 16:20:00 -0800268 // Rethrow stored error.
Andreas Gampe99babb62015-11-02 16:20:00 -0800269 HandleEarlierVerifyError(self, this, c);
Andreas Gampecb086952015-11-02 16:20:00 -0800270 }
Alex Lightd6251582016-10-31 11:12:30 -0700271 // TODO This might be wrong if we hit an OOME while allocating the ClassExt. In that case we
272 // might have meant to go down the earlier if statement with the original error but it got
273 // swallowed by the OOM so we end up here.
Vladimir Markobb206de2019-03-28 10:30:32 +0000274 if (verify_error == nullptr || wrap_in_no_class_def) {
Andreas Gampecb086952015-11-02 16:20:00 -0800275 // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
276 // the top-level exception must be a NoClassDefFoundError. The potentially already pending
277 // exception will be a cause.
278 self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
David Sehr709b0702016-10-13 09:12:37 -0700279 c->PrettyDescriptor().c_str());
Ian Rogers7b078e82014-09-10 14:44:24 -0700280 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700281 }
282}
283
Brian Carlstromb23eab12014-10-08 17:55:21 -0700284static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700285 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromb23eab12014-10-08 17:55:21 -0700286 if (VLOG_IS_ON(class_linker)) {
287 std::string temp;
288 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000289 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700290 }
291}
292
293static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700294 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700295 Thread* self = Thread::Current();
296 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700297
298 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700299 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700300
Andreas Gampe1e8a3952016-11-30 10:13:19 -0800301 // Boot classpath classes should not fail initialization. This is a sanity debug check. This
302 // cannot in general be guaranteed, but in all likelihood leads to breakage down the line.
303 if (klass->GetClassLoader() == nullptr && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampe22f71d22016-11-21 10:10:08 -0800304 std::string tmp;
Alex Light5047d9f2018-03-09 15:44:31 -0800305 // We want to LOG(FATAL) on debug builds since this really shouldn't be happening but we need to
306 // make sure to only do it if we don't have AsyncExceptions being thrown around since those
307 // could have caused the error.
308 bool known_impossible = kIsDebugBuild && !Runtime::Current()->AreAsyncExceptionsThrown();
309 LOG(known_impossible ? FATAL : WARNING) << klass->GetDescriptor(&tmp)
310 << " failed initialization: "
311 << self->GetException()->Dump();
Andreas Gampe22f71d22016-11-21 10:10:08 -0800312 }
313
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700314 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700315 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
316 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700317
Elliott Hughesa4f94742012-05-29 16:28:38 -0700318 // We only wrap non-Error exceptions; an Error can just be used as-is.
319 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000320 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700321 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700322 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700323}
324
Fred Shih381e4ca2014-08-25 17:24:27 -0700325// Gap between two fields in object layout.
326struct FieldGap {
327 uint32_t start_offset; // The offset from the start of the object.
328 uint32_t size; // The gap size of 1, 2, or 4 bytes.
329};
330struct FieldGapsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800331 FieldGapsComparator() {
Fred Shih381e4ca2014-08-25 17:24:27 -0700332 }
333 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
334 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800335 // Sort by gap size, largest first. Secondary sort by starting offset.
Richard Uhlerfab67882015-07-13 17:00:35 -0700336 // Note that the priority queue returns the largest element, so operator()
337 // should return true if lhs is less than rhs.
338 return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700339 }
340};
Andreas Gampec55bb392018-09-21 00:02:02 +0000341using FieldGaps = std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator>;
Fred Shih381e4ca2014-08-25 17:24:27 -0700342
343// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800344static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700345 DCHECK(gaps != nullptr);
346
347 uint32_t current_offset = gap_start;
348 while (current_offset != gap_end) {
349 size_t remaining = gap_end - current_offset;
350 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
351 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
352 current_offset += sizeof(uint32_t);
353 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
354 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
355 current_offset += sizeof(uint16_t);
356 } else {
357 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
358 current_offset += sizeof(uint8_t);
359 }
360 DCHECK_LE(current_offset, gap_end) << "Overran gap";
361 }
362}
363// Shuffle fields forward, making use of gaps whenever possible.
364template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000365static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700366 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700367 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700368 FieldGaps* gaps)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700369 REQUIRES_SHARED(Locks::mutator_lock_) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700370 DCHECK(current_field_idx != nullptr);
371 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700372 DCHECK(gaps != nullptr);
373 DCHECK(field_offset != nullptr);
374
375 DCHECK(IsPowerOfTwo(n));
376 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700377 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700378 Primitive::Type type = field->GetTypeAsPrimitiveType();
379 if (Primitive::ComponentSize(type) < n) {
380 break;
381 }
382 if (!IsAligned<n>(field_offset->Uint32Value())) {
383 MemberOffset old_offset = *field_offset;
384 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
385 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
386 }
David Sehr709b0702016-10-13 09:12:37 -0700387 CHECK(type != Primitive::kPrimNot) << field->PrettyField(); // should be primitive types
Fred Shih381e4ca2014-08-25 17:24:27 -0700388 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700389 if (!gaps->empty() && gaps->top().size >= n) {
390 FieldGap gap = gaps->top();
391 gaps->pop();
Roland Levillain14d90572015-07-16 10:52:26 +0100392 DCHECK_ALIGNED(gap.start_offset, n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700393 field->SetOffset(MemberOffset(gap.start_offset));
394 if (gap.size > n) {
395 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
396 }
397 } else {
Roland Levillain14d90572015-07-16 10:52:26 +0100398 DCHECK_ALIGNED(field_offset->Uint32Value(), n);
Fred Shih381e4ca2014-08-25 17:24:27 -0700399 field->SetOffset(*field_offset);
400 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
401 }
402 ++(*current_field_idx);
403 }
404}
405
Mathieu Chartierd399f572019-04-17 12:34:19 -0700406ClassLinker::ClassLinker(InternTable* intern_table)
Andreas Gampe2af99022017-04-25 08:32:59 -0700407 : boot_class_table_(new ClassTable()),
408 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800409 class_roots_(nullptr),
Ian Rogers98379392014-02-24 16:53:16 -0800410 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700411 init_done_(false),
Vladimir Marko1998cd02017-01-13 13:02:58 +0000412 log_new_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700413 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800414 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800415 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100416 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800417 quick_to_interpreter_bridge_trampoline_(nullptr),
Andreas Gampec1ac9ee2017-07-24 22:35:49 -0700418 image_pointer_size_(kRuntimePointerSize),
Andreas Gampe7dface32017-07-25 21:32:59 -0700419 cha_(Runtime::Current()->IsAotCompiler() ? nullptr : new ClassHierarchyAnalysis()) {
420 // For CHA disabled during Aot, see b/34193647.
421
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700422 CHECK(intern_table_ != nullptr);
Andreas Gampe8ac75952015-06-02 21:01:45 -0700423 static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
424 "Array cache size wrong.");
425 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700426}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700427
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800428void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700429 ObjPtr<mirror::Class> c2 = FindSystemClass(self, descriptor);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800430 if (c2 == nullptr) {
431 LOG(FATAL) << "Could not find class " << descriptor;
432 UNREACHABLE();
433 }
434 if (c1.Get() != c2) {
435 std::ostringstream os1, os2;
436 c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
437 c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
438 LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
439 << ". This is most likely the result of a broken build. Make sure that "
440 << "libcore and art projects match.\n\n"
441 << os1.str() << "\n\n" << os2.str();
442 UNREACHABLE();
443 }
444}
445
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800446bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
447 std::string* error_msg) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800448 VLOG(startup) << "ClassLinker::Init";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700449
Mathieu Chartiere401d142015-04-22 13:56:20 -0700450 Thread* const self = Thread::Current();
451 Runtime* const runtime = Runtime::Current();
452 gc::Heap* const heap = runtime->GetHeap();
453
Jeff Haodcdc85b2015-12-04 14:06:18 -0800454 CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700455 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700456
Mathieu Chartiere401d142015-04-22 13:56:20 -0700457 // Use the pointer size from the runtime since we are probably creating the image.
458 image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
459
Elliott Hughes30646832011-10-13 16:59:46 -0700460 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartier590fee92013-09-13 13:46:47 -0700461 // 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 -0800462 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700463 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700464 auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
Mathieu Chartierd7a7f2f2018-09-07 11:57:18 -0700465 // Allocate the object as non-movable so that there are no cases where Object::IsClass returns
466 // the incorrect result when comparing to-space vs from-space.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +0000467 Handle<mirror::Class> java_lang_Class(hs.NewHandle(ObjPtr<mirror::Class>::DownCast(
468 heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor()))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800469 CHECK(java_lang_Class != nullptr);
Vladimir Marko317892b2018-05-31 11:11:32 +0100470 java_lang_Class->SetClassFlags(mirror::kClassFlagClass);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700471 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700472 if (kUseBakerReadBarrier) {
473 java_lang_Class->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800474 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700475 java_lang_Class->SetClassSize(class_class_size);
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700476 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800477 heap->DecrementDisableMovingGC(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700478 // AllocClass(ObjPtr<mirror::Class>) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700479
Elliott Hughes418d20f2011-09-22 14:00:39 -0700480 // Class[] is used for reflection support.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700481 auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700482 Handle<mirror::Class> class_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700483 AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700484 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700485
Ian Rogers23435d02012-09-24 11:23:12 -0700486 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700487 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700488 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800489 CHECK(java_lang_Object != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700490 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700491 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000492 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700493
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700494 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800495 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
496 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
497 runtime->SetSentinel(heap->AllocNonMovableObject<true>(self,
498 java_lang_Object.Get(),
499 java_lang_Object->GetObjectSize(),
500 VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700501
Igor Murashkin86083f72017-10-27 10:59:04 -0700502 // Initialize the SubtypeCheck bitstring for java.lang.Object and java.lang.Class.
Vladimir Marko305c38b2018-02-14 11:50:07 +0000503 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -0700504 // It might seem the lock here is unnecessary, however all the SubtypeCheck
505 // functions are annotated to require locks all the way down.
506 //
507 // We take the lock here to avoid using NO_THREAD_SAFETY_ANALYSIS.
508 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +0000509 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Object.Get());
510 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(java_lang_Class.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -0700511 }
512
Ian Rogers23435d02012-09-24 11:23:12 -0700513 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700514 Handle<mirror::Class> object_array_class(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700515 AllocClass(self, java_lang_Class.Get(),
516 mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700517 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700518
Roland Levillain0e840272018-08-23 19:55:30 +0100519 // Setup java.lang.String.
520 //
521 // We make this class non-movable for the unlikely case where it were to be
522 // moved by a sticky-bit (minor) collection when using the Generational
523 // Concurrent Copying (CC) collector, potentially creating a stale reference
524 // in the `klass_` field of one of its instances allocated in the Large-Object
525 // Space (LOS) -- see the comment about the dirty card scanning logic in
526 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700527 Handle<mirror::Class> java_lang_String(hs.NewHandle(
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700528 AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +0100529 self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700530 java_lang_String->SetStringClass();
Vladimir Marko2c64a832018-01-04 11:31:56 +0000531 mirror::Class::SetStatus(java_lang_String, ClassStatus::kResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400532
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700533 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700534 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700535 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
Fred Shih4ee7a662014-07-11 09:59:27 -0700536 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000537 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700538
Ian Rogers23435d02012-09-24 11:23:12 -0700539 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700540 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100541 mirror::ObjectArray<mirror::Class>::Alloc(self,
542 object_array_class.Get(),
543 static_cast<int32_t>(ClassRoot::kMax)));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700544 CHECK(!class_roots_.IsNull());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100545 SetClassRoot(ClassRoot::kJavaLangClass, java_lang_Class.Get());
546 SetClassRoot(ClassRoot::kJavaLangObject, java_lang_Object.Get());
547 SetClassRoot(ClassRoot::kClassArrayClass, class_array_class.Get());
548 SetClassRoot(ClassRoot::kObjectArrayClass, object_array_class.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100549 SetClassRoot(ClassRoot::kJavaLangString, java_lang_String.Get());
550 SetClassRoot(ClassRoot::kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700551
Mathieu Chartier6beced42016-11-15 15:51:31 -0800552 // Fill in the empty iftable. Needs to be done after the kObjectArrayClass root is set.
553 java_lang_Object->SetIfTable(AllocIfTable(self, 0));
554
Vladimir Marko02610552018-06-04 14:38:00 +0100555 // Create array interface entries to populate once we can load system classes.
556 object_array_class->SetIfTable(AllocIfTable(self, 2));
557 DCHECK_EQ(GetArrayIfTable(), object_array_class->GetIfTable());
558
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700559 // Setup the primitive type classes.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100560 SetClassRoot(ClassRoot::kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
561 SetClassRoot(ClassRoot::kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
Vladimir Markoacb906d2018-05-30 10:23:49 +0100562 SetClassRoot(ClassRoot::kPrimitiveChar, CreatePrimitiveClass(self, Primitive::kPrimChar));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100563 SetClassRoot(ClassRoot::kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
564 SetClassRoot(ClassRoot::kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
565 SetClassRoot(ClassRoot::kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
566 SetClassRoot(ClassRoot::kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
567 SetClassRoot(ClassRoot::kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
568 SetClassRoot(ClassRoot::kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700569
Vladimir Markoacb906d2018-05-30 10:23:49 +0100570 // Create int array type for native pointer arrays (for example vtables) on 32-bit archs.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700571 Handle<mirror::Class> int_array_class(hs.NewHandle(
Roland Levillain0e840272018-08-23 19:55:30 +0100572 AllocPrimitiveArrayClass(self, java_lang_Class.Get())));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100573 int_array_class->SetComponentType(GetClassRoot(ClassRoot::kPrimitiveInt, this));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100574 SetClassRoot(ClassRoot::kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700575
Vladimir Markoacb906d2018-05-30 10:23:49 +0100576 // Create long array type for native pointer arrays (for example vtables) on 64-bit archs.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700577 Handle<mirror::Class> long_array_class(hs.NewHandle(
Roland Levillain0e840272018-08-23 19:55:30 +0100578 AllocPrimitiveArrayClass(self, java_lang_Class.Get())));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100579 long_array_class->SetComponentType(GetClassRoot(ClassRoot::kPrimitiveLong, this));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100580 SetClassRoot(ClassRoot::kLongArrayClass, long_array_class.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700581
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700582 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700583
Ian Rogers52813c92012-10-11 11:50:38 -0700584 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700585 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
Mathieu Chartiere401d142015-04-22 13:56:20 -0700586 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100587 SetClassRoot(ClassRoot::kJavaLangDexCache, java_lang_DexCache.Get());
Vladimir Marko05792b92015-08-03 11:56:49 +0100588 java_lang_DexCache->SetDexCacheClass();
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700589 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000590 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700591
Alex Lightd6251582016-10-31 11:12:30 -0700592
593 // Setup dalvik.system.ClassExt
594 Handle<mirror::Class> dalvik_system_ClassExt(hs.NewHandle(
595 AllocClass(self, java_lang_Class.Get(), mirror::ClassExt::ClassSize(image_pointer_size_))));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100596 SetClassRoot(ClassRoot::kDalvikSystemClassExt, dalvik_system_ClassExt.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000597 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kResolved, self);
Alex Lightd6251582016-10-31 11:12:30 -0700598
Mathieu Chartier66f19252012-09-18 08:57:04 -0700599 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700600 Handle<mirror::Class> object_array_string(hs.NewHandle(
601 AllocClass(self, java_lang_Class.Get(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700602 mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700603 object_array_string->SetComponentType(java_lang_String.Get());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100604 SetClassRoot(ClassRoot::kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700605
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000606 LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700607 // Create runtime resolution and imt conflict methods.
608 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
Nicolas Geoffray796d6302016-03-13 22:22:31 +0000609 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
610 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
Ian Rogers4445a7e2012-10-05 17:19:13 -0700611
Ian Rogers23435d02012-09-24 11:23:12 -0700612 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
613 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
614 // these roots.
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800615 if (boot_class_path.empty()) {
616 *error_msg = "Boot classpath is empty.";
617 return false;
618 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800619 for (auto& dex_file : boot_class_path) {
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800620 if (dex_file.get() == nullptr) {
621 *error_msg = "Null dex file.";
622 return false;
623 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700624 AppendToBootClassPath(self, *dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800625 boot_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700626 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700627
628 // now we can use FindSystemClass
629
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700630 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
631 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700632 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800633 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700634 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700635 quick_resolution_trampoline_ = GetQuickResolutionStub();
636 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
637 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700638 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700639
Alex Lightd6251582016-10-31 11:12:30 -0700640 // Object, String, ClassExt and DexCache need to be rerun through FindSystemClass to finish init
Vladimir Marko2c64a832018-01-04 11:31:56 +0000641 mirror::Class::SetStatus(java_lang_Object, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800642 CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700643 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000644 mirror::Class::SetStatus(java_lang_String, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800645 CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
Vladimir Marko2c64a832018-01-04 11:31:56 +0000646 mirror::Class::SetStatus(java_lang_DexCache, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800647 CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700648 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Vladimir Marko2c64a832018-01-04 11:31:56 +0000649 mirror::Class::SetStatus(dalvik_system_ClassExt, ClassStatus::kNotReady, self);
Alex Lightd6251582016-10-31 11:12:30 -0700650 CheckSystemClass(self, dalvik_system_ClassExt, "Ldalvik/system/ClassExt;");
651 CHECK_EQ(dalvik_system_ClassExt->GetObjectSize(), mirror::ClassExt::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700652
Ian Rogers23435d02012-09-24 11:23:12 -0700653 // Setup the primitive array type classes - can't be done until Object has a vtable.
Roland Levillain0e840272018-08-23 19:55:30 +0100654 AllocAndSetPrimitiveArrayClassRoot(self,
655 java_lang_Class.Get(),
656 ClassRoot::kBooleanArrayClass,
657 ClassRoot::kPrimitiveBoolean,
658 "[Z");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700659
Roland Levillain0e840272018-08-23 19:55:30 +0100660 AllocAndSetPrimitiveArrayClassRoot(
661 self, java_lang_Class.Get(), ClassRoot::kByteArrayClass, ClassRoot::kPrimitiveByte, "[B");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700662
Roland Levillain0e840272018-08-23 19:55:30 +0100663 AllocAndSetPrimitiveArrayClassRoot(
664 self, java_lang_Class.Get(), ClassRoot::kCharArrayClass, ClassRoot::kPrimitiveChar, "[C");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700665
Roland Levillain0e840272018-08-23 19:55:30 +0100666 AllocAndSetPrimitiveArrayClassRoot(
667 self, java_lang_Class.Get(), ClassRoot::kShortArrayClass, ClassRoot::kPrimitiveShort, "[S");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700668
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800669 CheckSystemClass(self, int_array_class, "[I");
670 CheckSystemClass(self, long_array_class, "[J");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700671
Roland Levillain0e840272018-08-23 19:55:30 +0100672 AllocAndSetPrimitiveArrayClassRoot(
673 self, java_lang_Class.Get(), ClassRoot::kFloatArrayClass, ClassRoot::kPrimitiveFloat, "[F");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700674
Roland Levillain0e840272018-08-23 19:55:30 +0100675 AllocAndSetPrimitiveArrayClassRoot(
676 self, java_lang_Class.Get(), ClassRoot::kDoubleArrayClass, ClassRoot::kPrimitiveDouble, "[D");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700677
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800678 // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
679 // in class_table_.
680 CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
Elliott Hughes418d20f2011-09-22 14:00:39 -0700681
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800682 CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;");
683 CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700684
Ian Rogers23435d02012-09-24 11:23:12 -0700685 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700686 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800687 CHECK(java_lang_Cloneable != nullptr);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700688 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
Andreas Gampefa4333d2017-02-14 11:10:34 -0800689 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700690 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
691 // crawl up and explicitly list all of the supers as well.
Vladimir Marko02610552018-06-04 14:38:00 +0100692 object_array_class->GetIfTable()->SetInterface(0, java_lang_Cloneable.Get());
693 object_array_class->GetIfTable()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700694
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700695 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
696 // suspension.
697 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000698 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700699 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000700 mirror::Class::GetDirectInterface(self, class_array_class.Get(), 1));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700701 CHECK_EQ(java_lang_Cloneable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000702 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 0));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700703 CHECK_EQ(java_io_Serializable.Get(),
Vladimir Marko19a4d372016-12-08 14:41:46 +0000704 mirror::Class::GetDirectInterface(self, object_array_class.Get(), 1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700705
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700706 CHECK_EQ(object_array_string.Get(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100707 FindSystemClass(self, GetClassRootDescriptor(ClassRoot::kJavaLangStringArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700708
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800709 // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700710
Ian Rogers23435d02012-09-24 11:23:12 -0700711 // Create java.lang.reflect.Proxy root.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100712 SetClassRoot(ClassRoot::kJavaLangReflectProxy,
713 FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700714
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700715 // Create java.lang.reflect.Field.class root.
Vladimir Markoacb906d2018-05-30 10:23:49 +0100716 ObjPtr<mirror::Class> class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700717 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100718 SetClassRoot(ClassRoot::kJavaLangReflectField, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700719
720 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700721 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
722 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100723 SetClassRoot(ClassRoot::kJavaLangReflectFieldArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700724
725 // Create java.lang.reflect.Constructor.class root and array root.
726 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
727 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100728 SetClassRoot(ClassRoot::kJavaLangReflectConstructor, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700729 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
730 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100731 SetClassRoot(ClassRoot::kJavaLangReflectConstructorArrayClass, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700732
733 // Create java.lang.reflect.Method.class root and array root.
734 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
735 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100736 SetClassRoot(ClassRoot::kJavaLangReflectMethod, class_root);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700737 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
738 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100739 SetClassRoot(ClassRoot::kJavaLangReflectMethodArrayClass, class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700740
Orion Hodson005ac512017-10-24 15:43:43 +0100741 // Create java.lang.invoke.CallSite.class root
742 class_root = FindSystemClass(self, "Ljava/lang/invoke/CallSite;");
743 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100744 SetClassRoot(ClassRoot::kJavaLangInvokeCallSite, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100745
Narayan Kamathafa48272016-08-03 12:46:58 +0100746 // Create java.lang.invoke.MethodType.class root
747 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodType;");
748 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100749 SetClassRoot(ClassRoot::kJavaLangInvokeMethodType, class_root);
Narayan Kamathafa48272016-08-03 12:46:58 +0100750
751 // Create java.lang.invoke.MethodHandleImpl.class root
752 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandleImpl;");
753 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100754 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandleImpl, class_root);
Vladimir Markoc7aa87e2018-05-24 15:19:52 +0100755 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandle, class_root->GetSuperClass());
Narayan Kamathafa48272016-08-03 12:46:58 +0100756
Orion Hodsonc069a302017-01-18 09:23:12 +0000757 // Create java.lang.invoke.MethodHandles.Lookup.class root
758 class_root = FindSystemClass(self, "Ljava/lang/invoke/MethodHandles$Lookup;");
759 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100760 SetClassRoot(ClassRoot::kJavaLangInvokeMethodHandlesLookup, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000761
Orion Hodson005ac512017-10-24 15:43:43 +0100762 // Create java.lang.invoke.VarHandle.class root
763 class_root = FindSystemClass(self, "Ljava/lang/invoke/VarHandle;");
Orion Hodsonc069a302017-01-18 09:23:12 +0000764 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100765 SetClassRoot(ClassRoot::kJavaLangInvokeVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100766
767 // Create java.lang.invoke.FieldVarHandle.class root
768 class_root = FindSystemClass(self, "Ljava/lang/invoke/FieldVarHandle;");
769 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100770 SetClassRoot(ClassRoot::kJavaLangInvokeFieldVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100771
772 // Create java.lang.invoke.ArrayElementVarHandle.class root
773 class_root = FindSystemClass(self, "Ljava/lang/invoke/ArrayElementVarHandle;");
774 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100775 SetClassRoot(ClassRoot::kJavaLangInvokeArrayElementVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100776
777 // Create java.lang.invoke.ByteArrayViewVarHandle.class root
778 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteArrayViewVarHandle;");
779 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100780 SetClassRoot(ClassRoot::kJavaLangInvokeByteArrayViewVarHandle, class_root);
Orion Hodson005ac512017-10-24 15:43:43 +0100781
782 // Create java.lang.invoke.ByteBufferViewVarHandle.class root
783 class_root = FindSystemClass(self, "Ljava/lang/invoke/ByteBufferViewVarHandle;");
784 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100785 SetClassRoot(ClassRoot::kJavaLangInvokeByteBufferViewVarHandle, class_root);
Orion Hodsonc069a302017-01-18 09:23:12 +0000786
Narayan Kamath000e1882016-10-24 17:14:25 +0100787 class_root = FindSystemClass(self, "Ldalvik/system/EmulatedStackFrame;");
788 CHECK(class_root != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100789 SetClassRoot(ClassRoot::kDalvikSystemEmulatedStackFrame, class_root);
Narayan Kamath000e1882016-10-24 17:14:25 +0100790
Brian Carlstrom1f870082011-08-23 16:02:11 -0700791 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700792 // finish initializing Reference class
Vladimir Marko2c64a832018-01-04 11:31:56 +0000793 mirror::Class::SetStatus(java_lang_ref_Reference, ClassStatus::kNotReady, self);
Andreas Gampe7ba5a672016-02-04 21:45:01 -0800794 CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
Fred Shih4ee7a662014-07-11 09:59:27 -0700795 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700796 CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
797 mirror::Reference::ClassSize(image_pointer_size_));
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700798 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
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::kClassFlagFinalizerReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700801 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
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::kClassFlagPhantomReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700804 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
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::kClassFlagSoftReference);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700807 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -0700808 CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -0700809 class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700810
Ian Rogers23435d02012-09-24 11:23:12 -0700811 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700812 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700813 class_root->SetClassLoaderClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700814 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100815 SetClassRoot(ClassRoot::kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700816
jeffhao8cd6dda2012-02-22 10:15:34 -0800817 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700818 // java.lang.StackTraceElement as a convenience.
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100819 SetClassRoot(ClassRoot::kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100820 SetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
Brian Carlstromf3632832014-05-20 15:36:53 -0700821 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100822 SetClassRoot(ClassRoot::kJavaLangStackTraceElement,
823 FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
824 SetClassRoot(ClassRoot::kJavaLangStackTraceElementArrayClass,
Brian Carlstromf3632832014-05-20 15:36:53 -0700825 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000826 SetClassRoot(ClassRoot::kJavaLangClassLoaderArrayClass,
827 FindSystemClass(self, "[Ljava/lang/ClassLoader;"));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700828
Mathieu Chartiercdca4762016-04-28 09:44:54 -0700829 // Create conflict tables that depend on the class linker.
830 runtime->FixupConflictTables();
831
Ian Rogers98379392014-02-24 16:53:16 -0800832 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700833
Brian Carlstroma004aa92012-02-08 18:05:09 -0800834 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Andreas Gampe3db9c5d2015-11-17 11:52:46 -0800835
836 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700837}
838
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700839static void CreateStringInitBindings(Thread* self, ClassLinker* class_linker)
840 REQUIRES_SHARED(Locks::mutator_lock_) {
841 // Find String.<init> -> StringFactory bindings.
842 ObjPtr<mirror::Class> string_factory_class =
843 class_linker->FindSystemClass(self, "Ljava/lang/StringFactory;");
844 CHECK(string_factory_class != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100845 ObjPtr<mirror::Class> string_class = GetClassRoot<mirror::String>(class_linker);
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700846 WellKnownClasses::InitStringInit(string_class, string_factory_class);
847 // Update the primordial thread.
848 self->InitStringEntryPoints();
849}
850
Ian Rogers98379392014-02-24 16:53:16 -0800851void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800852 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700853
Andreas Gampe9abc31e2018-05-17 11:47:09 -0700854 CreateStringInitBindings(self, this);
855
Brian Carlstrom16192862011-09-12 17:50:06 -0700856 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700857 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700858 // as the types of the field can't be resolved prior to the runtime being
859 // fully initialized
Andreas Gampe7b2450e2018-06-19 10:45:54 -0700860 StackHandleScope<3> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100861 Handle<mirror::Class> java_lang_ref_Reference =
862 hs.NewHandle(GetClassRoot<mirror::Reference>(this));
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700863 Handle<mirror::Class> java_lang_ref_FinalizerReference =
864 hs.NewHandle(FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800865
Mathieu Chartierc7853442015-03-27 14:35:38 -0700866 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700867 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
868 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700869
Mathieu Chartierc7853442015-03-27 14:35:38 -0700870 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700871 CHECK_STREQ(queue->GetName(), "queue");
872 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700873
Mathieu Chartierc7853442015-03-27 14:35:38 -0700874 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700875 CHECK_STREQ(queueNext->GetName(), "queueNext");
876 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700877
Mathieu Chartierc7853442015-03-27 14:35:38 -0700878 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700879 CHECK_STREQ(referent->GetName(), "referent");
880 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700881
Mathieu Chartierc7853442015-03-27 14:35:38 -0700882 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700883 CHECK_STREQ(zombie->GetName(), "zombie");
884 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700885
Brian Carlstroma663ea52011-08-19 23:33:41 -0700886 // ensure all class_roots_ are initialized
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100887 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700888 ClassRoot class_root = static_cast<ClassRoot>(i);
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700889 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700890 CHECK(klass != nullptr);
891 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700892 // note SetClassRoot does additional validation.
893 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700894 }
895
Vladimir Marko02610552018-06-04 14:38:00 +0100896 CHECK(GetArrayIfTable() != nullptr);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700897
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700898 // disable the slow paths in FindClass and CreatePrimitiveClass now
899 // that Object, Class, and Object[] are setup
900 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700901
Andreas Gampe7b2450e2018-06-19 10:45:54 -0700902 // Under sanitization, the small carve-out to handle stack overflow might not be enough to
903 // initialize the StackOverflowError class (as it might require running the verifier). Instead,
904 // ensure that the class will be initialized.
905 if (kMemoryToolIsAvailable && !Runtime::Current()->IsAotCompiler()) {
Andreas Gampea43ba3d2019-03-13 15:49:20 -0700906 verifier::ClassVerifier::Init(); // Need to prepare the verifier.
Andreas Gampe7b2450e2018-06-19 10:45:54 -0700907
908 ObjPtr<mirror::Class> soe_klass = FindSystemClass(self, "Ljava/lang/StackOverflowError;");
909 if (soe_klass == nullptr || !EnsureInitialized(self, hs.NewHandle(soe_klass), true, true)) {
910 // Strange, but don't crash.
911 LOG(WARNING) << "Could not prepare StackOverflowError.";
912 self->ClearException();
913 }
914 }
915
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800916 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700917}
918
Vladimir Markodcfcce42018-06-27 10:00:28 +0000919void ClassLinker::RunRootClinits(Thread* self) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100920 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); ++i) {
921 ObjPtr<mirror::Class> c = GetClassRoot(ClassRoot(i), this);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700922 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700923 StackHandleScope<1> hs(self);
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100924 Handle<mirror::Class> h_class(hs.NewHandle(c));
Ian Rogers7b078e82014-09-10 14:44:24 -0700925 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700926 self->AssertNoPendingException();
Vladimir Markodcfcce42018-06-27 10:00:28 +0000927 } else {
928 DCHECK(c->IsInitialized());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700929 }
930 }
931}
932
Jeff Haodcdc85b2015-12-04 14:06:18 -0800933struct TrampolineCheckData {
934 const void* quick_resolution_trampoline;
935 const void* quick_imt_conflict_trampoline;
936 const void* quick_generic_jni_trampoline;
937 const void* quick_to_interpreter_bridge_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -0700938 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800939 ArtMethod* m;
940 bool error;
941};
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800942
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800943bool ClassLinker::InitFromBootImage(std::string* error_msg) {
944 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700945 CHECK(!init_done_);
946
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700947 Runtime* const runtime = Runtime::Current();
948 Thread* const self = Thread::Current();
949 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800950 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
951 CHECK(!spaces.empty());
Andreas Gampe542451c2016-07-26 09:02:02 -0700952 uint32_t pointer_size_unchecked = spaces[0]->GetImageHeader().GetPointerSizeUnchecked();
953 if (!ValidPointerSize(pointer_size_unchecked)) {
954 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800955 return false;
956 }
Vladimir Marko3364d182019-03-13 13:55:01 +0000957 const ImageHeader& image_header = spaces[0]->GetImageHeader();
958 image_pointer_size_ = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800959 if (!runtime->IsAotCompiler()) {
960 // Only the Aot compiler supports having an image with a different pointer size than the
961 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
962 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -0700963 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800964 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -0700965 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800966 sizeof(void*));
967 return false;
968 }
969 }
Vladimir Marko3364d182019-03-13 13:55:01 +0000970 DCHECK(!runtime->HasResolutionMethod());
971 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
972 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
973 runtime->SetImtUnimplementedMethod(
974 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
975 runtime->SetCalleeSaveMethod(
976 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
977 CalleeSaveType::kSaveAllCalleeSaves);
978 runtime->SetCalleeSaveMethod(
979 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
980 CalleeSaveType::kSaveRefsOnly);
981 runtime->SetCalleeSaveMethod(
982 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
983 CalleeSaveType::kSaveRefsAndArgs);
984 runtime->SetCalleeSaveMethod(
985 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
986 CalleeSaveType::kSaveEverything);
987 runtime->SetCalleeSaveMethod(
988 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
989 CalleeSaveType::kSaveEverythingForClinit);
990 runtime->SetCalleeSaveMethod(
991 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
992 CalleeSaveType::kSaveEverythingForSuspendCheck);
993
Jeff Haodcdc85b2015-12-04 14:06:18 -0800994 std::vector<const OatFile*> oat_files =
995 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
996 DCHECK(!oat_files.empty());
997 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800998 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
999 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
1000 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
1001 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
1002 if (kIsDebugBuild) {
1003 // Check that the other images use the same trampoline.
1004 for (size_t i = 1; i < oat_files.size(); ++i) {
1005 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
1006 const void* ith_quick_resolution_trampoline =
1007 ith_oat_header.GetQuickResolutionTrampoline();
1008 const void* ith_quick_imt_conflict_trampoline =
1009 ith_oat_header.GetQuickImtConflictTrampoline();
1010 const void* ith_quick_generic_jni_trampoline =
1011 ith_oat_header.GetQuickGenericJniTrampoline();
1012 const void* ith_quick_to_interpreter_bridge_trampoline =
1013 ith_oat_header.GetQuickToInterpreterBridge();
1014 if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
1015 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1016 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
1017 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
1018 // Make sure that all methods in this image do not contain those trampolines as
1019 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1020 TrampolineCheckData data;
1021 data.error = false;
1022 data.pointer_size = GetImagePointerSize();
1023 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1024 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1025 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1026 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
1027 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001028 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1029 if (obj->IsClass()) {
1030 ObjPtr<mirror::Class> klass = obj->AsClass();
1031 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1032 const void* entrypoint =
1033 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1034 if (entrypoint == data.quick_resolution_trampoline ||
1035 entrypoint == data.quick_imt_conflict_trampoline ||
1036 entrypoint == data.quick_generic_jni_trampoline ||
1037 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1038 data.m = &m;
1039 data.error = true;
1040 return;
1041 }
1042 }
1043 }
1044 };
1045 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001046 if (data.error) {
1047 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001048 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001049 *error_msg = "Found an ArtMethod with a bad entrypoint";
1050 return false;
1051 }
1052 }
1053 }
1054 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001055
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001056 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00001057 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(
1058 spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)));
Vladimir Markof75613c2018-06-05 12:51:04 +01001059 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001060
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001061 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001062 java_lang_Object->SetObjectSize(sizeof(mirror::Object));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001063 // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
1064 // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001065 runtime->SetSentinel(heap->AllocNonMovableObject<true>(
1066 self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001067
Vladimir Marko4433c432018-12-04 14:57:47 +00001068 const std::vector<std::string>& boot_class_path_locations = runtime->GetBootClassPathLocations();
1069 CHECK_LE(spaces.size(), boot_class_path_locations.size());
Vladimir Markod1908512018-11-22 14:57:28 +00001070 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001071 // Boot class loader, use a null handle.
1072 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001073 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001074 ScopedNullHandle<mirror::ClassLoader>(),
Vladimir Markod1908512018-11-22 14:57:28 +00001075 /*dex_elements=*/ nullptr,
Vladimir Marko4433c432018-12-04 14:57:47 +00001076 /*dex_location=*/ boot_class_path_locations[i].c_str(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001077 /*out*/&dex_files,
1078 error_msg)) {
1079 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001080 }
David Brazdil3e8aae02019-03-26 18:48:02 +00001081 // Assert that if absolute boot classpath locations were provided, they were
1082 // assigned to the loaded dex files.
1083 if (kIsDebugBuild && IsAbsoluteLocation(boot_class_path_locations[i])) {
1084 for (const auto& dex_file : dex_files) {
1085 DCHECK_EQ(DexFileLoader::GetBaseLocation(dex_file->GetLocation()),
1086 boot_class_path_locations[i]);
1087 }
1088 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001089 // Append opened dex files at the end.
1090 boot_dex_files_.insert(boot_dex_files_.end(),
1091 std::make_move_iterator(dex_files.begin()),
1092 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001093 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001094 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1095 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1096 }
Ian Rogers98379392014-02-24 16:53:16 -08001097 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001098
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001099 VLOG(startup) << __FUNCTION__ << " exiting";
1100 return true;
1101}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001102
Vladimir Marko4433c432018-12-04 14:57:47 +00001103void ClassLinker::AddExtraBootDexFiles(
1104 Thread* self,
1105 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1106 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
1107 AppendToBootClassPath(self, *dex_file);
1108 boot_dex_files_.push_back(std::move(dex_file));
1109 }
1110}
1111
Jeff Hao5872d7c2016-04-27 11:07:41 -07001112bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001113 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001114 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001115 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1116 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001117}
1118
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001119static bool GetDexPathListElementName(ObjPtr<mirror::Object> element,
1120 ObjPtr<mirror::String>* out_name)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001121 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001122 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001123 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001124 ArtField* const dex_file_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001125 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001126 DCHECK(dex_file_field != nullptr);
1127 DCHECK(dex_file_name_field != nullptr);
1128 DCHECK(element != nullptr);
David Sehr709b0702016-10-13 09:12:37 -07001129 CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << element->PrettyTypeOf();
Mathieu Chartier3398c782016-09-30 10:27:43 -07001130 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001131 if (dex_file == nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001132 // Null dex file means it was probably a jar with no dex files, return a null string.
1133 *out_name = nullptr;
1134 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001135 }
Mathieu Chartier3398c782016-09-30 10:27:43 -07001136 ObjPtr<mirror::Object> name_object = dex_file_name_field->GetObject(dex_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001137 if (name_object != nullptr) {
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001138 *out_name = name_object->AsString();
1139 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001140 }
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08001141 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001142}
1143
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001144static bool GetDexFileNames(ScopedObjectAccessUnchecked& soa,
1145 ObjPtr<mirror::ClassLoader> class_loader,
1146 /*out*/std::list<ObjPtr<mirror::String>>* dex_files,
1147 /*out*/std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001148 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001149 StackHandleScope<1> hs(soa.Self());
1150 Handle<mirror::ClassLoader> handle(hs.NewHandle(class_loader));
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001151 // Get element names. Sets error to true on failure.
1152 auto add_element_names = [&](ObjPtr<mirror::Object> element, bool* error)
1153 REQUIRES_SHARED(Locks::mutator_lock_) {
1154 if (element == nullptr) {
1155 *error_msg = "Null dex element";
1156 *error = true; // Null element is a critical error.
1157 return false; // Had an error, stop the visit.
1158 }
1159 ObjPtr<mirror::String> name;
1160 if (!GetDexPathListElementName(element, &name)) {
1161 *error_msg = "Invalid dex path list element";
1162 *error = true; // Invalid element, make it a critical error.
1163 return false; // Stop the visit.
1164 }
1165 if (name != nullptr) {
1166 dex_files->push_front(name);
1167 }
1168 return true; // Continue with the next Element.
1169 };
1170 bool error = VisitClassLoaderDexElements(soa,
1171 handle,
1172 add_element_names,
1173 /*defaultReturn=*/ false);
1174 return !error;
1175}
1176
1177static bool CompareClassLoaderTypes(ScopedObjectAccessUnchecked& soa,
1178 ObjPtr<mirror::ClassLoader> image_class_loader,
1179 ObjPtr<mirror::ClassLoader> class_loader,
1180 std::string* error_msg)
1181 REQUIRES_SHARED(Locks::mutator_lock_) {
1182 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1183 if (!ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1184 *error_msg = "Hierarchies don't match";
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001185 return false;
1186 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001187 } else if (ClassLinker::IsBootClassLoader(soa, image_class_loader)) {
1188 *error_msg = "Hierarchies don't match";
1189 return false;
1190 } else if (class_loader->GetClass() != image_class_loader->GetClass()) {
1191 *error_msg = StringPrintf("Class loader types don't match %s and %s",
1192 image_class_loader->PrettyTypeOf().c_str(),
1193 class_loader->PrettyTypeOf().c_str());
1194 return false;
1195 } else if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
1196 class_loader->GetClass()) {
1197 *error_msg = StringPrintf("Unknown class loader type %s",
1198 class_loader->PrettyTypeOf().c_str());
1199 // Unsupported class loader.
1200 return false;
1201 }
1202 return true;
1203}
1204
1205static bool CompareDexFiles(const std::list<ObjPtr<mirror::String>>& image_dex_files,
1206 const std::list<ObjPtr<mirror::String>>& loader_dex_files,
1207 std::string* error_msg)
1208 REQUIRES_SHARED(Locks::mutator_lock_) {
1209 bool equal = (image_dex_files.size() == loader_dex_files.size()) &&
1210 std::equal(image_dex_files.begin(),
1211 image_dex_files.end(),
1212 loader_dex_files.begin(),
1213 [](ObjPtr<mirror::String> lhs, ObjPtr<mirror::String> rhs)
1214 REQUIRES_SHARED(Locks::mutator_lock_) {
1215 return lhs->Equals(rhs);
1216 });
1217 if (!equal) {
1218 VLOG(image) << "Image dex files " << image_dex_files.size();
1219 for (ObjPtr<mirror::String> name : image_dex_files) {
1220 VLOG(image) << name->ToModifiedUtf8();
1221 }
1222 VLOG(image) << "Loader dex files " << loader_dex_files.size();
1223 for (ObjPtr<mirror::String> name : loader_dex_files) {
1224 VLOG(image) << name->ToModifiedUtf8();
1225 }
1226 *error_msg = "Mismatch in dex files";
1227 }
1228 return equal;
1229}
1230
1231static bool CompareClassLoaders(ScopedObjectAccessUnchecked& soa,
1232 ObjPtr<mirror::ClassLoader> image_class_loader,
1233 ObjPtr<mirror::ClassLoader> class_loader,
1234 bool check_dex_file_names,
1235 std::string* error_msg)
1236 REQUIRES_SHARED(Locks::mutator_lock_) {
1237 if (!CompareClassLoaderTypes(soa, image_class_loader, class_loader, error_msg)) {
1238 return false;
1239 }
1240
1241 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
1242 // No need to check further.
1243 return true;
1244 }
1245
1246 if (check_dex_file_names) {
1247 std::list<ObjPtr<mirror::String>> image_dex_files;
1248 if (!GetDexFileNames(soa, image_class_loader, &image_dex_files, error_msg)) {
Andreas Gampeb8e7c372018-02-20 18:24:55 -08001249 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001250 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001251
1252 std::list<ObjPtr<mirror::String>> loader_dex_files;
1253 if (!GetDexFileNames(soa, class_loader, &loader_dex_files, error_msg)) {
1254 return false;
1255 }
1256
1257 if (!CompareDexFiles(image_dex_files, loader_dex_files, error_msg)) {
1258 return false;
1259 }
1260 }
1261
1262 ArtField* field =
1263 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
1264 ObjPtr<mirror::Object> shared_libraries_image_loader = field->GetObject(image_class_loader.Ptr());
1265 ObjPtr<mirror::Object> shared_libraries_loader = field->GetObject(class_loader.Ptr());
1266 if (shared_libraries_image_loader == nullptr) {
1267 if (shared_libraries_loader != nullptr) {
1268 *error_msg = "Mismatch in shared libraries";
1269 return false;
1270 }
1271 } else if (shared_libraries_loader == nullptr) {
1272 *error_msg = "Mismatch in shared libraries";
1273 return false;
1274 } else {
1275 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array1 =
1276 shared_libraries_image_loader->AsObjectArray<mirror::ClassLoader>();
1277 ObjPtr<mirror::ObjectArray<mirror::ClassLoader>> array2 =
1278 shared_libraries_loader->AsObjectArray<mirror::ClassLoader>();
1279 if (array1->GetLength() != array2->GetLength()) {
1280 *error_msg = "Mismatch in number of shared libraries";
1281 return false;
1282 }
1283
1284 for (int32_t i = 0; i < array1->GetLength(); ++i) {
1285 // Do a full comparison of the class loaders, including comparing their dex files.
1286 if (!CompareClassLoaders(soa,
1287 array1->Get(i),
1288 array2->Get(i),
1289 /*check_dex_file_names=*/ true,
1290 error_msg)) {
1291 return false;
1292 }
1293 }
1294 }
1295
1296 // Do a full comparison of the class loaders, including comparing their dex files.
1297 if (!CompareClassLoaders(soa,
1298 image_class_loader->GetParent(),
1299 class_loader->GetParent(),
1300 /*check_dex_file_names=*/ true,
1301 error_msg)) {
1302 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001303 }
1304 return true;
1305}
1306
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001307class CHAOnDeleteUpdateClassVisitor {
1308 public:
1309 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1310 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1311 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1312 self_(Thread::Current()) {}
1313
1314 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1315 // This class is going to be unloaded. Tell CHA about it.
1316 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1317 return true;
1318 }
1319 private:
1320 const LinearAlloc* allocator_;
1321 const ClassHierarchyAnalysis* cha_;
1322 const PointerSize pointer_size_;
1323 const Thread* self_;
1324};
1325
Chris Wailes0c61be42018-09-26 17:27:34 -07001326/*
1327 * A class used to ensure that all strings in an AppImage have been properly
Chris Wailesfbeef462018-10-19 14:16:35 -07001328 * interned, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001329 */
1330class VerifyStringInterningVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001331 public:
Chris Wailes0c61be42018-09-26 17:27:34 -07001332 explicit VerifyStringInterningVisitor(const gc::space::ImageSpace& space) :
Chris Wailes0c61be42018-09-26 17:27:34 -07001333 space_(space),
1334 intern_table_(*Runtime::Current()->GetInternTable()) {}
1335
Chris Wailes0c61be42018-09-26 17:27:34 -07001336 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001337 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001338 if (referred_obj != nullptr &&
1339 space_.HasAddress(referred_obj.Ptr()) &&
1340 referred_obj->IsString()) {
1341 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Chris Wailesfbeef462018-10-19 14:16:35 -07001342
1343 if (kIsDebugBuild) {
1344 // Saved to temporary variables to aid in debugging.
1345 ObjPtr<mirror::String> strong_lookup_result =
1346 intern_table_.LookupStrong(Thread::Current(), referred_str);
1347 ObjPtr<mirror::String> weak_lookup_result =
1348 intern_table_.LookupWeak(Thread::Current(), referred_str);
1349
1350 DCHECK((strong_lookup_result == referred_str) || (weak_lookup_result == referred_str));
1351 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001352 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001353 }
1354
Chris Wailes0c61be42018-09-26 17:27:34 -07001355 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001356 mirror::CompressedReference<mirror::Object>* root) const
1357 REQUIRES_SHARED(Locks::mutator_lock_) {
1358 if (!root->IsNull()) {
1359 VisitRoot(root);
1360 }
1361 }
1362
Chris Wailes0c61be42018-09-26 17:27:34 -07001363 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001364 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001365 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001366 }
1367
1368 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001369 void operator()(ObjPtr<mirror::Object> obj,
1370 MemberOffset offset,
1371 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001372 REQUIRES_SHARED(Locks::mutator_lock_) {
1373 // There could be overlap between ranges, we must avoid visiting the same reference twice.
1374 // Avoid the class field since we already fixed it up in FixupClassVisitor.
1375 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
1376 // Updating images, don't do a read barrier.
Chris Wailes0c61be42018-09-26 17:27:34 -07001377 ObjPtr<mirror::Object> referred_obj =
1378 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1379
1380 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001381 }
1382 }
1383
1384 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1385 ObjPtr<mirror::Reference> ref) const
1386 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001387 operator()(ref, mirror::Reference::ReferentOffset(), false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001388 }
1389
Chris Wailes0c61be42018-09-26 17:27:34 -07001390 const gc::space::ImageSpace& space_;
1391 InternTable& intern_table_;
Chang Xingba17dbd2017-06-28 21:27:56 +00001392};
1393
Chris Wailes0c61be42018-09-26 17:27:34 -07001394/*
1395 * This function verifies that string references in the AppImage have been
1396 * properly interned. To be considered properly interned a reference must
1397 * point to the same version of the string that the intern table does.
1398 */
Chris Wailesfbeef462018-10-19 14:16:35 -07001399void VerifyStringInterning(gc::space::ImageSpace& space) REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001400 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1401 const ImageHeader& image_header = space.GetImageHeader();
1402 const uint8_t* target_base = space.GetMemMap()->Begin();
1403 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001404
1405 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1406 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001407
1408 VerifyStringInterningVisitor visitor(space);
1409 bitmap->VisitMarkedRange(objects_begin,
1410 objects_end,
1411 [&space, &visitor](mirror::Object* obj)
1412 REQUIRES_SHARED(Locks::mutator_lock_) {
1413 if (space.HasAddress(obj)) {
1414 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001415 obj->VisitReferences</* kVisitNativeRoots= */ true,
1416 kVerifyNone,
1417 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001418 } else {
1419 // Don't visit native roots for non-dex-cache as they can't contain
1420 // native references to strings. This is verified during compilation
1421 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001422 obj->VisitReferences</* kVisitNativeRoots= */ false,
1423 kVerifyNone,
1424 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001425 }
1426 }
1427 });
Chris Wailes0c61be42018-09-26 17:27:34 -07001428}
1429
Andreas Gampe2af99022017-04-25 08:32:59 -07001430// new_class_set is the set of classes that were read from the class table section in the image.
1431// If there was no class table section, it is null.
1432// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001433class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001434 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001435 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001436 ClassLinker* class_linker,
1437 gc::space::ImageSpace* space,
1438 Handle<mirror::ClassLoader> class_loader,
1439 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001440 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001441 REQUIRES(!Locks::dex_lock_)
1442 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001443
Chris Wailesfbeef462018-10-19 14:16:35 -07001444 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001445 REQUIRES_SHARED(Locks::mutator_lock_);
1446
1447 static void UpdateInternStrings(
1448 gc::space::ImageSpace* space,
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001449 bool use_preresolved_strings,
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001450 const SafeMap<mirror::String*, mirror::String*>& intern_remap)
1451 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001452};
1453
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001454void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001455 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001456 gc::space::ImageSpace* space,
1457 Handle<mirror::ClassLoader> class_loader,
1458 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001459 ClassTable::ClassSet* new_class_set)
Andreas Gampe2af99022017-04-25 08:32:59 -07001460 REQUIRES(!Locks::dex_lock_)
1461 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001462 ScopedTrace app_image_timing("AppImage:Updating");
1463
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001464 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001465 Runtime* const runtime = Runtime::Current();
1466 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001467 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001468 bool load_app_image_startup_cache = runtime->LoadAppImageStartupCache();
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 Chartiera88abfa2019-02-04 11:08:29 -08001482 if (!load_app_image_startup_cache) {
1483 dex_cache->ClearPreResolvedStrings();
1484 }
1485
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001486 if (kIsDebugBuild) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001487 CHECK(new_class_set != nullptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001488 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Marko1a1de672016-10-13 12:53:15 +01001489 const size_t num_types = dex_cache->NumResolvedTypes();
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001490 for (size_t j = 0; j != num_types; ++j) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001491 // The image space is not yet added to the heap, avoid read barriers.
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001492 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Chris Wailes0c61be42018-09-26 17:27:34 -07001493
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001494 if (space->HasAddress(klass.Ptr())) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001495 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Vladimir Marko54159c62018-06-20 14:30:08 +01001496 auto it = new_class_set->find(ClassTable::TableSlot(klass));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001497 DCHECK(it != new_class_set->end());
1498 DCHECK_EQ(it->Read(), klass);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001499 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Chris Wailes0c61be42018-09-26 17:27:34 -07001500
Vladimir Marko1a1de672016-10-13 12:53:15 +01001501 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
Vladimir Marko54159c62018-06-20 14:30:08 +01001502 auto it2 = new_class_set->find(ClassTable::TableSlot(super_class));
Vladimir Marko1a1de672016-10-13 12:53:15 +01001503 DCHECK(it2 != new_class_set->end());
1504 DCHECK_EQ(it2->Read(), super_class);
1505 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001506
Vladimir Marko1a1de672016-10-13 12:53:15 +01001507 for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
1508 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001509 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1510 if (!class_linker->IsQuickResolutionStub(code) &&
1511 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001512 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001513 !m.IsNative()) {
1514 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartier69731002016-03-02 16:08:31 -08001515 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001516 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001517
Vladimir Marko1a1de672016-10-13 12:53:15 +01001518 for (ArtMethod& m : klass->GetVirtualMethods(kRuntimePointerSize)) {
1519 const void* code = m.GetEntryPointFromQuickCompiledCode();
Alex Lightfc49fec2018-01-16 22:28:36 +00001520 const void* oat_code = m.IsInvokable() ? class_linker->GetQuickOatCodeFor(&m) : code;
1521 if (!class_linker->IsQuickResolutionStub(code) &&
1522 !class_linker->IsQuickGenericJniStub(code) &&
Andreas Gampe2af99022017-04-25 08:32:59 -07001523 !class_linker->IsQuickToInterpreterBridge(code) &&
Alex Lightfc49fec2018-01-16 22:28:36 +00001524 !m.IsNative()) {
1525 DCHECK_EQ(code, oat_code) << m.PrettyMethod();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001526 }
1527 }
1528 }
1529 }
1530 }
1531 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001532 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001533
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001534 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001535 HandleAppImageStrings(space);
1536
1537 if (kIsDebugBuild) {
1538 VerifyStringInterning(*space);
1539 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001540 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001541
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001542 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001543 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001544 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001545 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1546 header.VisitPackedArtMethods([&](ArtMethod& method)
1547 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1548 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1549 if (klass != nullptr) {
1550 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1551 }
1552 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001553 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001554}
1555
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001556void AppImageLoadingHelper::UpdateInternStrings(
1557 gc::space::ImageSpace* space,
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001558 bool use_preresolved_strings,
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001559 const SafeMap<mirror::String*, mirror::String*>& intern_remap) {
1560 const uint8_t* target_base = space->Begin();
Chris Wailesfbeef462018-10-19 14:16:35 -07001561 const ImageSection& sro_section =
1562 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1563 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001564 InternTable* const intern_table = Runtime::Current()->GetInternTable();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001565
1566 VLOG(image)
1567 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1568 << num_string_offsets;
1569
Chris Wailesfbeef462018-10-19 14:16:35 -07001570 const auto* sro_base =
1571 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001572
1573 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001574 uint32_t base_offset = sro_base[offset_index].first;
1575
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001576 if (HasDexCacheStringNativeRefTag(base_offset)) {
1577 base_offset = ClearDexCacheNativeRefTags(base_offset);
1578 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001579
1580 ObjPtr<mirror::DexCache> dex_cache =
1581 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1582 uint32_t string_index = sro_base[offset_index].second;
1583
1584 mirror::StringDexCachePair source = dex_cache->GetStrings()[string_index].load();
1585 ObjPtr<mirror::String> referred_string = source.object.Read();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001586 DCHECK(referred_string != nullptr);
1587
Chris Wailesfbeef462018-10-19 14:16:35 -07001588 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001589 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001590 // This doesn't use SetResolvedString to maintain consistency with how
1591 // we load the string. The index from the source string must be
1592 // re-used due to the circular nature of the cache. Because we are not
1593 // using a helper function we need to mark the GC card manually.
1594 WriteBarrier::ForEveryFieldWrite(dex_cache);
1595 dex_cache->GetStrings()[string_index].store(
1596 mirror::StringDexCachePair(it->second, source.index));
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001597 } else if (!use_preresolved_strings) {
1598 dex_cache->GetStrings()[string_index].store(
1599 mirror::StringDexCachePair(intern_table->InternStrong(referred_string), source.index));
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001600 }
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001601 } else if (HasDexCachePreResolvedStringNativeRefTag(base_offset)) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001602 if (use_preresolved_strings) {
1603 base_offset = ClearDexCacheNativeRefTags(base_offset);
1604 DCHECK_ALIGNED(base_offset, 2);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001605
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001606 ObjPtr<mirror::DexCache> dex_cache =
1607 reinterpret_cast<mirror::DexCache*>(space->Begin() + base_offset);
1608 uint32_t string_index = sro_base[offset_index].second;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001609
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001610 ObjPtr<mirror::String> referred_string =
1611 dex_cache->GetPreResolvedStrings()[string_index].Read();
1612 DCHECK(referred_string != nullptr);
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001613
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001614 auto it = intern_remap.find(referred_string.Ptr());
1615 if (it != intern_remap.end()) {
1616 // Because we are not using a helper function we need to mark the GC card manually.
1617 WriteBarrier::ForEveryFieldWrite(dex_cache);
1618 dex_cache->GetPreResolvedStrings()[string_index] = GcRoot<mirror::String>(it->second);
1619 }
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001620 }
Chris Wailesfbeef462018-10-19 14:16:35 -07001621 } else {
1622 uint32_t raw_member_offset = sro_base[offset_index].second;
Mathieu Chartier1ca718e2018-10-23 12:55:34 -07001623 DCHECK_ALIGNED(base_offset, 2);
Chris Wailesfbeef462018-10-19 14:16:35 -07001624 DCHECK_ALIGNED(raw_member_offset, 2);
1625
1626 ObjPtr<mirror::Object> obj_ptr =
1627 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1628 MemberOffset member_offset(raw_member_offset);
1629 ObjPtr<mirror::String> referred_string =
1630 obj_ptr->GetFieldObject<mirror::String,
1631 kVerifyNone,
1632 kWithoutReadBarrier,
1633 /* kIsVolatile= */ false>(member_offset);
1634 DCHECK(referred_string != nullptr);
1635
1636 auto it = intern_remap.find(referred_string.Ptr());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001637 if (it != intern_remap.end()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001638 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1639 /* kCheckTransaction= */ false,
1640 kVerifyNone,
1641 /* kIsVolatile= */ false>(member_offset, it->second);
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001642 } else if (!use_preresolved_strings) {
1643 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1644 /* kCheckTransaction= */ false,
1645 kVerifyNone,
1646 /* kIsVolatile= */ false>(
1647 member_offset,
1648 intern_table->InternStrong(referred_string));
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001649 }
1650 }
1651 }
1652}
1653
Chris Wailesfbeef462018-10-19 14:16:35 -07001654void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001655 // Iterate over the string reference offsets stored in the image and intern
1656 // the strings they point to.
1657 ScopedTrace timing("AppImage:InternString");
1658
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001659 Runtime* const runtime = Runtime::Current();
1660 InternTable* const intern_table = runtime->GetInternTable();
1661
1662 const bool load_startup_cache = runtime->LoadAppImageStartupCache();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001663
1664 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1665 // for faster lookup.
1666 // TODO: Optimize with a bitmap or bloom filter
1667 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001668 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001669 REQUIRES_SHARED(Locks::mutator_lock_)
1670 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001671 const size_t non_boot_image_strings = intern_table->CountInterns(
1672 /*visit_boot_images=*/false,
1673 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001674 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001675 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1676 // Visit the smaller of the two sets to compute the intersection.
1677 if (interns.size() < non_boot_image_strings) {
1678 for (auto it = interns.begin(); it != interns.end(); ) {
1679 ObjPtr<mirror::String> string = it->Read();
1680 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1681 if (existing == nullptr) {
1682 existing = intern_table->LookupStrongLocked(string);
1683 }
1684 if (existing != nullptr) {
1685 intern_remap.Put(string.Ptr(), existing.Ptr());
1686 it = interns.erase(it);
1687 } else {
1688 ++it;
1689 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001690 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001691 } else {
1692 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1693 REQUIRES_SHARED(Locks::mutator_lock_)
1694 REQUIRES(Locks::intern_table_lock_) {
1695 auto it = interns.find(root);
1696 if (it != interns.end()) {
1697 ObjPtr<mirror::String> existing = root.Read();
1698 intern_remap.Put(it->Read(), existing.Ptr());
1699 it = interns.erase(it);
1700 }
1701 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1702 }
1703 // Sanity check to ensure correctness.
1704 if (kIsDebugBuild) {
1705 for (GcRoot<mirror::String>& root : interns) {
1706 ObjPtr<mirror::String> string = root.Read();
1707 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1708 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001709 }
1710 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001711 };
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001712
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001713 bool update_intern_strings;
1714 if (load_startup_cache) {
Mathieu Chartiere23b3882019-02-14 07:35:43 -08001715 VLOG(image) << "AppImage:load_startup_cache";
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001716 // Only add the intern table if we are using the startup cache. Otherwise,
1717 // UpdateInternStrings adds the strings to the intern table.
1718 intern_table->AddImageStringsToTable(space, func);
1719 update_intern_strings = kIsDebugBuild || !intern_remap.empty();
1720 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
1721 } else {
1722 update_intern_strings = true;
1723 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001724
1725 // For debug builds, always run the code below to get coverage.
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001726 if (update_intern_strings) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001727 // Slow path case is when there are conflicting intern strings to fix up.
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001728 UpdateInternStrings(space, /*use_preresolved_strings=*/ load_startup_cache, intern_remap);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001729 }
1730}
1731
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001732static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1733 const char* location,
1734 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001735 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001736 DCHECK(error_msg != nullptr);
1737 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001738 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001739 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001740 return std::unique_ptr<const DexFile>();
1741 }
1742 std::string inner_error_msg;
1743 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1744 if (dex_file == nullptr) {
1745 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1746 location,
1747 oat_file->GetLocation().c_str(),
1748 inner_error_msg.c_str());
1749 return std::unique_ptr<const DexFile>();
1750 }
1751
1752 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1753 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1754 location,
1755 dex_file->GetLocationChecksum(),
1756 oat_dex_file->GetDexFileLocationChecksum());
1757 return std::unique_ptr<const DexFile>();
1758 }
1759 return dex_file;
1760}
1761
1762bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1763 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1764 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001765 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001766 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001767 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001768 DCHECK(dex_caches_object != nullptr);
Vladimir Marko4617d582019-03-28 13:48:31 +00001769 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001770 dex_caches_object->AsObjectArray<mirror::DexCache>();
1771 const OatFile* oat_file = space->GetOatFile();
Vladimir Marko4617d582019-03-28 13:48:31 +00001772 for (int32_t i = 0, length = dex_caches->GetLength(); i != length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001773 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001774 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1775 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1776 dex_file_location.c_str(),
1777 error_msg);
1778 if (dex_file == nullptr) {
1779 return false;
1780 }
1781 dex_cache->SetDexFile(dex_file.get());
1782 out_dex_files->push_back(std::move(dex_file));
1783 }
1784 return true;
1785}
1786
Andreas Gampe0793bec2016-12-01 11:37:33 -08001787// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1788// together and caches some intermediate results.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001789class ImageSanityChecks final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001790 public:
1791 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1792 REQUIRES_SHARED(Locks::mutator_lock_) {
1793 ImageSanityChecks isc(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001794 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1795 DCHECK(obj != nullptr);
1796 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1797 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1798 if (obj->IsClass()) {
1799 auto klass = obj->AsClass();
1800 for (ArtField& field : klass->GetIFields()) {
1801 CHECK_EQ(field.GetDeclaringClass(), klass);
1802 }
1803 for (ArtField& field : klass->GetSFields()) {
1804 CHECK_EQ(field.GetDeclaringClass(), klass);
1805 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001806 const PointerSize pointer_size = isc.pointer_size_;
1807 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001808 isc.SanityCheckArtMethod(&m, klass);
1809 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001810 ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001811 if (vtable != nullptr) {
1812 isc.SanityCheckArtMethodPointerArray(vtable, nullptr);
1813 }
1814 if (klass->ShouldHaveImt()) {
1815 ImTable* imt = klass->GetImt(pointer_size);
1816 for (size_t i = 0; i < ImTable::kSize; ++i) {
1817 isc.SanityCheckArtMethod(imt->Get(i, pointer_size), nullptr);
1818 }
1819 }
1820 if (klass->ShouldHaveEmbeddedVTable()) {
1821 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
1822 isc.SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
1823 }
1824 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001825 ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001826 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1827 if (iftable->GetMethodArrayCount(i) > 0) {
1828 isc.SanityCheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
1829 }
1830 }
1831 }
1832 };
1833 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001834 }
1835
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001836 static void CheckArtMethodDexCacheArray(gc::Heap* heap,
1837 ClassLinker* class_linker,
1838 mirror::MethodDexCacheType* arr,
1839 size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001840 REQUIRES_SHARED(Locks::mutator_lock_) {
1841 ImageSanityChecks isc(heap, class_linker);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001842 isc.SanityCheckArtMethodDexCacheArray(arr, size);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001843 }
1844
Andreas Gampe0793bec2016-12-01 11:37:33 -08001845 private:
1846 ImageSanityChecks(gc::Heap* heap, ClassLinker* class_linker)
1847 : spaces_(heap->GetBootImageSpaces()),
1848 pointer_size_(class_linker->GetImagePointerSize()) {
1849 space_begin_.reserve(spaces_.size());
1850 method_sections_.reserve(spaces_.size());
1851 runtime_method_sections_.reserve(spaces_.size());
1852 for (gc::space::ImageSpace* space : spaces_) {
1853 space_begin_.push_back(space->Begin());
1854 auto& header = space->GetImageHeader();
1855 method_sections_.push_back(&header.GetMethodsSection());
1856 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1857 }
1858 }
1859
1860 void SanityCheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
1861 REQUIRES_SHARED(Locks::mutator_lock_) {
1862 if (m->IsRuntimeMethod()) {
1863 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1864 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1865 } else if (m->IsCopied()) {
1866 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1867 } else if (expected_class != nullptr) {
1868 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1869 }
1870 if (!spaces_.empty()) {
1871 bool contains = false;
1872 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1873 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1874 contains = method_sections_[i]->Contains(offset) ||
1875 runtime_method_sections_[i]->Contains(offset);
1876 }
1877 CHECK(contains) << m << " not found";
1878 }
1879 }
1880
1881 void SanityCheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1882 ObjPtr<mirror::Class> expected_class)
1883 REQUIRES_SHARED(Locks::mutator_lock_) {
1884 CHECK(arr != nullptr);
1885 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1886 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1887 // expected_class == null means we are a dex cache.
1888 if (expected_class != nullptr) {
1889 CHECK(method != nullptr);
1890 }
1891 if (method != nullptr) {
1892 SanityCheckArtMethod(method, expected_class);
1893 }
1894 }
1895 }
1896
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001897 void SanityCheckArtMethodDexCacheArray(mirror::MethodDexCacheType* arr, size_t size)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001898 REQUIRES_SHARED(Locks::mutator_lock_) {
1899 CHECK_EQ(arr != nullptr, size != 0u);
1900 if (arr != nullptr) {
1901 bool contains = false;
1902 for (auto space : spaces_) {
1903 auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001904 if (space->GetImageHeader().GetDexCacheArraysSection().Contains(offset)) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001905 contains = true;
1906 break;
1907 }
1908 }
1909 CHECK(contains);
1910 }
1911 for (size_t j = 0; j < size; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001912 auto pair = mirror::DexCache::GetNativePairPtrSize(arr, j, pointer_size_);
1913 ArtMethod* method = pair.object;
Andreas Gampe0793bec2016-12-01 11:37:33 -08001914 // expected_class == null means we are a dex cache.
1915 if (method != nullptr) {
1916 SanityCheckArtMethod(method, nullptr);
1917 }
1918 }
1919 }
1920
1921 const std::vector<gc::space::ImageSpace*>& spaces_;
1922 const PointerSize pointer_size_;
1923
1924 // Cached sections from the spaces.
1925 std::vector<const uint8_t*> space_begin_;
1926 std::vector<const ImageSection*> method_sections_;
1927 std::vector<const ImageSection*> runtime_method_sections_;
1928};
1929
Andreas Gampebe7af222017-07-25 09:57:28 -07001930static void VerifyAppImage(const ImageHeader& header,
1931 const Handle<mirror::ClassLoader>& class_loader,
1932 const Handle<mirror::ObjectArray<mirror::DexCache> >& dex_caches,
1933 ClassTable* class_table, gc::space::ImageSpace* space)
1934 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001935 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1936 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
1937 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1938 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
1939 << mirror::Class::PrettyClass(klass);
1940 }
1941 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07001942 {
1943 // Verify that all direct interfaces of classes in the class table are also resolved.
1944 std::vector<ObjPtr<mirror::Class>> classes;
1945 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1946 REQUIRES_SHARED(Locks::mutator_lock_) {
1947 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1948 classes.push_back(klass);
1949 }
1950 return true;
1951 };
1952 class_table->Visit(verify_direct_interfaces_in_table);
1953 Thread* self = Thread::Current();
1954 for (ObjPtr<mirror::Class> klass : classes) {
1955 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1956 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1957 << klass->PrettyDescriptor() << " iface #" << i;
1958 }
1959 }
1960 }
1961 // Check that all non-primitive classes in dex caches are also in the class table.
1962 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1963 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
1964 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
1965 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
1966 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
1967 if (klass != nullptr && !klass->IsPrimitive()) {
1968 CHECK(class_table->Contains(klass))
1969 << klass->PrettyDescriptor() << " " << dex_cache->GetDexFile()->GetLocation();
1970 }
1971 }
1972 }
1973}
1974
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001975bool ClassLinker::AddImageSpace(
1976 gc::space::ImageSpace* space,
1977 Handle<mirror::ClassLoader> class_loader,
1978 jobjectArray dex_elements,
1979 const char* dex_location,
1980 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1981 std::string* error_msg) {
1982 DCHECK(out_dex_files != nullptr);
1983 DCHECK(error_msg != nullptr);
1984 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001985 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001986 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001987 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001988 DCHECK(dex_caches_object != nullptr);
1989 Runtime* const runtime = Runtime::Current();
1990 gc::Heap* const heap = runtime->GetHeap();
1991 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001992 // Check that the image is what we are expecting.
1993 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1994 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1995 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1996 image_pointer_size_);
1997 return false;
1998 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001999 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
2000 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
2001 *error_msg = StringPrintf("Expected %zu image roots but got %d",
2002 expected_image_roots,
2003 header.GetImageRoots()->GetLength());
2004 return false;
2005 }
2006 StackHandleScope<3> hs(self);
2007 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
2008 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
2009 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
2010 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002011 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01002012 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
2013 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002014 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002015 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002016 *error_msg = StringPrintf("Expected %d class roots but got %d",
2017 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002018 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002019 return false;
2020 }
2021 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002022 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
2023 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
2024 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002025 *error_msg = "App image class roots must have pointer equality with runtime ones.";
2026 return false;
2027 }
2028 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002029 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002030 if (oat_file->GetOatHeader().GetDexFileCount() !=
2031 static_cast<uint32_t>(dex_caches->GetLength())) {
2032 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
2033 "image";
2034 return false;
2035 }
2036
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002037 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Markocd556b02017-02-03 11:47:34 +00002038 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
David Brazdil3e8aae02019-03-26 18:48:02 +00002039 std::string dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
Andreas Gamped5d807b2019-04-18 14:46:51 -07002040 if (class_loader == nullptr) {
2041 // For app images, we'll see the relative location. b/130666977.
2042 DCHECK_EQ(dex_location, DexFileLoader::GetBaseLocation(dex_file_location));
2043 }
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08002044 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
2045 dex_file_location.c_str(),
2046 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002047 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002048 return false;
2049 }
2050
2051 if (app_image) {
2052 // The current dex file field is bogus, overwrite it so that we can get the dex file in the
2053 // loop below.
Vladimir Markocd556b02017-02-03 11:47:34 +00002054 dex_cache->SetDexFile(dex_file.get());
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002055 mirror::TypeDexCacheType* const types = dex_cache->GetResolvedTypes();
Vladimir Markocd556b02017-02-03 11:47:34 +00002056 for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002057 ObjPtr<mirror::Class> klass = types[j].load(std::memory_order_relaxed).object.Read();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002058 if (klass != nullptr) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00002059 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002060 }
2061 }
2062 } else {
2063 if (kSanityCheckObjects) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002064 ImageSanityChecks::CheckArtMethodDexCacheArray(heap,
2065 this,
2066 dex_cache->GetResolvedMethods(),
2067 dex_cache->NumResolvedMethods());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002068 }
2069 // Register dex files, keep track of existing ones that are conflicts.
Vladimir Markocd556b02017-02-03 11:47:34 +00002070 AppendToBootClassPath(*dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002071 }
2072 out_dex_files->push_back(std::move(dex_file));
2073 }
2074
2075 if (app_image) {
2076 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002077 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002078 // Check that the class loader resolves the same way as the ones in the image.
2079 // Image class loader [A][B][C][image dex files]
2080 // Class loader = [???][dex_elements][image dex files]
2081 // Need to ensure that [???][dex_elements] == [A][B][C].
David Brazdil05909d82018-12-06 16:25:16 +00002082 // For each class loader, PathClassLoader, the loader checks the parent first. Also the logic
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002083 // for PathClassLoader does this by looping through the array of dex files. To ensure they
2084 // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
2085 // and check that the dex file names are the same.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002086 if (IsBootClassLoader(soa, image_class_loader.Get())) {
2087 *error_msg = "Unexpected BootClassLoader in app image";
2088 return false;
2089 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002090 // The dex files of `class_loader` are not setup yet, so we cannot do a full comparison
2091 // of `class_loader` and `image_class_loader` in `CompareClassLoaders`. Therefore, we
2092 // special case the comparison of dex files of the two class loaders, but then do full
2093 // comparisons for their shared libraries and parent.
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002094 auto elements = soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements);
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002095 std::list<ObjPtr<mirror::String>> loader_dex_file_names;
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002096 for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
2097 ObjPtr<mirror::Object> element = elements->GetWithoutChecks(i);
2098 if (element != nullptr) {
2099 // If we are somewhere in the middle of the array, there may be nulls at the end.
Mathieu Chartier8a1691f2017-03-02 12:02:13 -08002100 ObjPtr<mirror::String> name;
2101 if (GetDexPathListElementName(element, &name) && name != nullptr) {
2102 loader_dex_file_names.push_back(name);
2103 }
Nicolas Geoffray1df3b552016-04-26 18:30:31 +01002104 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002105 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002106 std::string temp_error_msg;
2107 std::list<ObjPtr<mirror::String>> image_dex_file_names;
2108 bool success = GetDexFileNames(
2109 soa, image_class_loader.Get(), &image_dex_file_names, &temp_error_msg);
2110 if (success) {
2111 // Ignore the number of image dex files since we are adding those to the class loader anyways.
2112 CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
2113 static_cast<size_t>(dex_caches->GetLength()));
2114 size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
2115 image_dex_file_names.resize(image_count);
2116 success = success && CompareDexFiles(image_dex_file_names,
2117 loader_dex_file_names,
2118 &temp_error_msg);
2119 success = success && CompareClassLoaders(soa,
2120 image_class_loader.Get(),
2121 class_loader.Get(),
2122 /*check_dex_file_names=*/ false,
2123 &temp_error_msg);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00002124 }
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00002125 if (!success) {
2126 *error_msg = StringPrintf("Rejecting application image due to class loader mismatch: '%s'",
2127 temp_error_msg.c_str());
2128 return false;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002129 }
2130 }
2131
2132 if (kSanityCheckObjects) {
2133 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Vladimir Marko423bebb2019-03-26 15:17:21 +00002134 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002135 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
2136 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
2137 if (field != nullptr) {
2138 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
2139 }
2140 }
2141 }
2142 if (!app_image) {
Andreas Gampe0793bec2016-12-01 11:37:33 -08002143 ImageSanityChecks::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002144 }
2145 }
2146
2147 // Set entry point to interpreter if in InterpretOnly mode.
2148 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07002149 // Set image methods' entry point to interpreter.
2150 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2151 if (!method.IsRuntimeMethod()) {
2152 DCHECK(method.GetDeclaringClass() != nullptr);
2153 if (!method.IsNative() && !method.IsResolutionMethod()) {
2154 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
2155 image_pointer_size_);
2156 }
2157 }
2158 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002159 }
2160
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002161 ClassTable* class_table = nullptr;
2162 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002163 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002164 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002165 }
2166 // If we have a class table section, read it and use it for verification in
2167 // UpdateAppImageClassLoadersAndDexCaches.
2168 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002169 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002170 const bool added_class_table = class_table_section.Size() > 0u;
2171 if (added_class_table) {
2172 const uint64_t start_time2 = NanoTime();
2173 size_t read_count = 0;
2174 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2175 /*make copy*/false,
2176 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002177 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002178 }
2179 if (app_image) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07002180 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches, &temp_set);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002181
2182 {
2183 ScopedTrace trace("AppImage:UpdateClassLoaders");
2184 // Update class loader and resolved strings. If added_class_table is false, the resolved
2185 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002186 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002187 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002188 // Note: We probably don't need the read barrier unless we copy the app image objects into
2189 // the region space.
2190 ObjPtr<mirror::Class> klass(root.Read());
2191 // Do not update class loader for boot image classes where the app image
2192 // class loader is only the initiating loader but not the defining loader.
2193 // Avoid read barrier since we are comparing against null.
2194 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
2195 klass->SetClassLoader</*kCheckTransaction=*/ false>(loader);
2196 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002197 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002198 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002199
Vladimir Marko305c38b2018-02-14 11:50:07 +00002200 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002201 // Every class in the app image has initially SubtypeCheckInfo in the
2202 // Uninitialized state.
2203 //
2204 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2205 // after class initialization is complete. The app image ClassStatus as-is
2206 // are almost all ClassStatus::Initialized, and being in the
2207 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2208 //
2209 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2210 //
2211 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002212 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002213 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2214 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002215 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002216 }
2217 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002218 }
2219 if (!oat_file->GetBssGcRoots().empty()) {
2220 // Insert oat file to class table for visiting .bss GC roots.
2221 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002222 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002223
Mathieu Chartier69731002016-03-02 16:08:31 -08002224 if (added_class_table) {
2225 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2226 class_table->AddClassSet(std::move(temp_set));
2227 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002228
Mathieu Chartier69731002016-03-02 16:08:31 -08002229 if (kIsDebugBuild && app_image) {
2230 // This verification needs to happen after the classes have been added to the class loader.
2231 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002232 ScopedTrace trace("AppImage:Verify");
Andreas Gampebe7af222017-07-25 09:57:28 -07002233 VerifyAppImage(header, class_loader, dex_caches, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002234 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002235
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002236 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002237 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002238}
2239
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002240bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002241 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2242 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002243}
2244
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002245void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002246 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2247 // enabling tracing requires the mutator lock, there are no race conditions here.
2248 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002249 Thread* const self = Thread::Current();
2250 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002251 if (kUseReadBarrier) {
2252 // We do not track new roots for CC.
2253 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2254 kVisitRootFlagClearRootLog |
2255 kVisitRootFlagStartLoggingNewRoots |
2256 kVisitRootFlagStopLoggingNewRoots));
2257 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002258 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002259 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2260 // There is 3 GC cases to handle:
2261 // Non moving concurrent:
2262 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002263 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002264 //
2265 // Moving non-concurrent:
2266 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2267 // To prevent missing roots, this case needs to ensure that there is no
2268 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2269 // class which is in the class table.
2270 //
2271 // Moving concurrent:
2272 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2273 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002274 //
2275 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2276 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2277 // these objects.
2278 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002279 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002280 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002281 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002282 for (const ClassLoaderData& data : class_loaders_) {
2283 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2284 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2285 }
2286 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002287 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002288 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002289 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002290 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002291 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002292 // Concurrent moving GC marked new roots through the to-space invariant.
2293 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002294 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002295 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2296 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2297 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2298 if (old_ref != nullptr) {
2299 DCHECK(old_ref->IsClass());
2300 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2301 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2302 // Concurrent moving GC marked new roots through the to-space invariant.
2303 CHECK_EQ(new_ref, old_ref);
2304 }
2305 }
2306 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002307 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002308 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002309 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002310 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002311 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002312 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002313 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002314 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002315 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002316 }
2317 // We deliberately ignore the class roots in the image since we
2318 // handle image roots by using the MS/CMS rescanning of dirty cards.
2319}
2320
Brian Carlstroma663ea52011-08-19 23:33:41 -07002321// Keep in sync with InitCallback. Anything we visit, we need to
2322// reinit references to when reinitializing a ClassLinker from a
2323// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002324void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002325 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002326 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002327 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2328 // unloading if we are marking roots.
2329 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002330}
2331
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002332class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2333 public:
2334 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2335 : visitor_(visitor),
2336 done_(false) {}
2337
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002338 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002339 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002340 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002341 if (!done_ && class_table != nullptr) {
2342 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2343 if (!class_table->Visit(visitor)) {
2344 // If the visitor ClassTable returns false it means that we don't need to continue.
2345 done_ = true;
2346 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002347 }
2348 }
2349
2350 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002351 // Class visitor that limits the class visits from a ClassTable to the classes with
2352 // the provided defining class loader. This filter is used to avoid multiple visits
2353 // of the same class which can be recorded for multiple initiating class loaders.
2354 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2355 public:
2356 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2357 ClassVisitor* visitor)
2358 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2359
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002360 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002361 if (klass->GetClassLoader() != defining_class_loader_) {
2362 return true;
2363 }
2364 return (*visitor_)(klass);
2365 }
2366
Vladimir Marko0984e482019-03-27 16:41:41 +00002367 const ObjPtr<mirror::ClassLoader> defining_class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002368 ClassVisitor* const visitor_;
2369 };
2370
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002371 ClassVisitor* const visitor_;
2372 // If done is true then we don't need to do any more visiting.
2373 bool done_;
2374};
2375
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002376void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002377 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002378 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2379 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002380 }
2381}
2382
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002383void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002384 Thread* const self = Thread::Current();
2385 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2386 // Not safe to have thread suspension when we are holding a lock.
2387 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002388 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002389 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002390 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002391 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002392 }
2393}
2394
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002395class GetClassesInToVector : public ClassVisitor {
2396 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002397 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002398 classes_.push_back(klass);
2399 return true;
2400 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002401 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002402};
2403
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002404class GetClassInToObjectArray : public ClassVisitor {
2405 public:
2406 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2407 : arr_(arr), index_(0) {}
2408
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002409 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002410 ++index_;
2411 if (index_ <= arr_->GetLength()) {
2412 arr_->Set(index_ - 1, klass);
2413 return true;
2414 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002415 return false;
2416 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002417
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002418 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002419 return index_ <= arr_->GetLength();
2420 }
2421
2422 private:
2423 mirror::ObjectArray<mirror::Class>* const arr_;
2424 int32_t index_;
2425};
2426
2427void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002428 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2429 // is avoiding duplicates.
2430 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002431 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002432 GetClassesInToVector accumulator;
2433 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002434 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002435 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002436 return;
2437 }
2438 }
2439 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002440 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002441 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002442 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002443 // We size the array assuming classes won't be added to the class table during the visit.
2444 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002445 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002446 size_t class_table_size;
2447 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002448 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002449 // Add 100 in case new classes get loaded when we are filling in the object array.
2450 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002451 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002452 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002453 classes.Assign(
2454 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002455 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002456 GetClassInToObjectArray accumulator(classes.Get());
2457 VisitClasses(&accumulator);
2458 if (accumulator.Succeeded()) {
2459 break;
2460 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002461 }
2462 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2463 // If the class table shrank during creation of the clases array we expect null elements. If
2464 // the class table grew then the loop repeats. If classes are created after the loop has
2465 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002466 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002467 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002468 return;
2469 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002470 }
2471 }
2472}
2473
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002474ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002475 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002476 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002477 // CHA unloading analysis is not needed. No negative consequences are expected because
2478 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002479 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002480 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002481 class_loaders_.clear();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002482}
2483
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002484void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002485 Runtime* const runtime = Runtime::Current();
2486 JavaVMExt* const vm = runtime->GetJavaVM();
2487 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002488 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002489 if (runtime->GetJit() != nullptr) {
2490 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2491 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002492 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002493 code_cache->RemoveMethodsIn(self, *data.allocator);
2494 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002495 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002496 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002497 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002498 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002499 // Cleanup references to single implementation ArtMethods that will be deleted.
2500 if (cleanup_cha) {
2501 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2502 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2503 }
2504
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002505 delete data.allocator;
2506 delete data.class_table;
2507}
2508
Vladimir Markobcf17522018-06-01 13:14:32 +01002509ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2510 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002511 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002512 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2513 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002514}
2515
Vladimir Markobcf17522018-06-01 13:14:32 +01002516ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(/*out*/ ObjPtr<mirror::String>* out_location,
2517 Thread* self,
2518 const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002519 StackHandleScope<1> hs(self);
2520 DCHECK(out_location != nullptr);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002521 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002522 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002523 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002524 self->AssertPendingOOMException();
2525 return nullptr;
2526 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002527 ObjPtr<mirror::String> location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002528 if (location == nullptr) {
2529 self->AssertPendingOOMException();
2530 return nullptr;
2531 }
2532 *out_location = location;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002533 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002534}
2535
Vladimir Markobcf17522018-06-01 13:14:32 +01002536ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2537 const DexFile& dex_file,
2538 LinearAlloc* linear_alloc) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002539 ObjPtr<mirror::String> location = nullptr;
2540 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(&location, self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002541 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002542 WriterMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002543 DCHECK(location != nullptr);
Andreas Gampecc1b5352016-12-01 16:58:38 -08002544 mirror::DexCache::InitializeDexCache(self,
2545 dex_cache,
2546 location,
2547 &dex_file,
2548 linear_alloc,
2549 image_pointer_size_);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002550 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002551 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002552}
2553
Roland Levillain0e840272018-08-23 19:55:30 +01002554template <bool kMovable>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002555ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2556 ObjPtr<mirror::Class> java_lang_Class,
2557 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002558 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002559 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002560 mirror::Class::InitializeClassVisitor visitor(class_size);
Roland Levillain0e840272018-08-23 19:55:30 +01002561 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Brian Carlstromf3632832014-05-20 15:36:53 -07002562 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2563 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002564 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002565 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002566 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002567 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002568 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002569}
2570
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002571ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002572 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002573}
2574
Roland Levillain0e840272018-08-23 19:55:30 +01002575ObjPtr<mirror::Class> ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2576 ObjPtr<mirror::Class> java_lang_Class) {
2577 // We make this class non-movable for the unlikely case where it were to be
2578 // moved by a sticky-bit (minor) collection when using the Generational
2579 // Concurrent Copying (CC) collector, potentially creating a stale reference
2580 // in the `klass_` field of one of its instances allocated in the Large-Object
2581 // Space (LOS) -- see the comment about the dirty card scanning logic in
2582 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002583 return AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01002584 self, java_lang_Class, mirror::Array::ClassSize(image_pointer_size_));
2585}
2586
Vladimir Markobcf17522018-06-01 13:14:32 +01002587ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002588 Thread* self,
2589 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002590 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002591 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002592}
2593
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002594ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2595 const char* descriptor,
2596 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002597 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002598 if (kIsDebugBuild) {
2599 StackHandleScope<1> hs(self);
2600 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2601 Thread::PoisonObjectPointersIfDebug();
2602 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002603
2604 // For temporary classes we must wait for them to be retired.
2605 if (init_done_ && klass->IsTemp()) {
2606 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002607 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002608 ThrowEarlierClassFailure(klass);
2609 return nullptr;
2610 }
2611 StackHandleScope<1> hs(self);
2612 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2613 ObjectLock<mirror::Class> lock(self, h_class);
2614 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002615 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002616 lock.WaitIgnoringInterrupts();
2617 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002618 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002619 ThrowEarlierClassFailure(h_class.Get());
2620 return nullptr;
2621 }
2622 CHECK(h_class->IsRetired());
2623 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002624 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002625 }
2626
Brian Carlstromaded5f72011-10-07 17:15:04 -07002627 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002628 size_t index = 0;
2629 // Maximum number of yield iterations until we start sleeping.
2630 static const size_t kNumYieldIterations = 1000;
2631 // How long each sleep is in us.
2632 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002633 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002634 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002635 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002636 {
2637 ObjectTryLock<mirror::Class> lock(self, h_class);
2638 // Can not use a monitor wait here since it may block when returning and deadlock if another
2639 // thread has locked klass.
2640 if (lock.Acquired()) {
2641 // Check for circular dependencies between classes, the lock is required for SetStatus.
2642 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2643 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002644 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002645 return nullptr;
2646 }
2647 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002648 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002649 {
2650 // Handle wrapper deals with klass moving.
2651 ScopedThreadSuspension sts(self, kSuspended);
2652 if (index < kNumYieldIterations) {
2653 sched_yield();
2654 } else {
2655 usleep(kSleepDurationUS);
2656 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002657 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002658 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002659 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002660
Vladimir Marko72ab6842017-01-20 19:32:50 +00002661 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002662 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002663 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002664 }
2665 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002666 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002667 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002668 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002669}
2670
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002671using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002672
2673// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002674ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002675 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002676 for (const DexFile* dex_file : class_path) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002677 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002678 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002679 return ClassPathEntry(dex_file, dex_class_def);
2680 }
2681 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002682 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002683}
2684
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002685bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2686 Thread* self,
2687 const char* descriptor,
2688 size_t hash,
2689 Handle<mirror::ClassLoader> class_loader,
2690 /*out*/ ObjPtr<mirror::Class>* result) {
2691 ArtField* field =
2692 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2693 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2694 if (raw_shared_libraries == nullptr) {
2695 return true;
2696 }
2697
2698 StackHandleScope<2> hs(self);
2699 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2700 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2701 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
2702 for (int32_t i = 0; i < shared_libraries->GetLength(); ++i) {
2703 temp_loader.Assign(shared_libraries->Get(i));
2704 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2705 return false; // One of the shared libraries is not supported.
2706 }
2707 if (*result != nullptr) {
2708 return true; // Found the class up the chain.
2709 }
2710 }
2711 return true;
2712}
2713
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002714bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2715 Thread* self,
2716 const char* descriptor,
2717 size_t hash,
2718 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002719 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002720 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002721 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002722 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002723 return true;
2724 }
2725
David Brazdil05909d82018-12-06 16:25:16 +00002726 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002727 // For regular path or dex class loader the search order is:
2728 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002729 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002730 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002731
Calin Juravlecdd49122017-07-05 20:09:53 -07002732 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2733 StackHandleScope<1> hs(self);
2734 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2735 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2736 return false; // One of the parents is not supported.
2737 }
2738 if (*result != nullptr) {
2739 return true; // Found the class up the chain.
2740 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002741
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002742 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2743 return false; // One of the shared library loader is not supported.
2744 }
2745 if (*result != nullptr) {
2746 return true; // Found the class in a shared library.
2747 }
2748
Calin Juravlecdd49122017-07-05 20:09:53 -07002749 // Search the current class loader classpath.
2750 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampe501c3b02019-04-17 21:54:27 +00002751 return !soa.Self()->IsExceptionPending();
Andreas Gampef865ea92015-04-13 22:14:19 -07002752 }
2753
Calin Juravlecdd49122017-07-05 20:09:53 -07002754 if (IsDelegateLastClassLoader(soa, class_loader)) {
2755 // For delegate last, the search order is:
2756 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002757 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002758 // - class loader dex files
2759 // - parent
2760 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2761 if (*result != nullptr) {
2762 return true; // The class is part of the boot class path.
2763 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002764 if (self->IsExceptionPending()) {
2765 // Pending exception means there was an error other than ClassNotFound that must be returned
2766 // to the caller.
2767 return false;
2768 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002769
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002770 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2771 return false; // One of the shared library loader is not supported.
2772 }
2773 if (*result != nullptr) {
2774 return true; // Found the class in a shared library.
2775 }
2776
Calin Juravlecdd49122017-07-05 20:09:53 -07002777 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2778 if (*result != nullptr) {
2779 return true; // Found the class in the current class loader
2780 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002781 if (self->IsExceptionPending()) {
2782 // Pending exception means there was an error other than ClassNotFound that must be returned
2783 // to the caller.
2784 return false;
2785 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002786
2787 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2788 StackHandleScope<1> hs(self);
2789 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2790 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2791 }
2792
2793 // Unsupported class loader.
2794 *result = nullptr;
2795 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002796}
2797
Andreas Gampe501c3b02019-04-17 21:54:27 +00002798namespace {
2799
2800// Matches exceptions caught in DexFile.defineClass.
2801ALWAYS_INLINE bool MatchesDexFileCaughtExceptions(ObjPtr<mirror::Throwable> throwable,
2802 ClassLinker* class_linker)
2803 REQUIRES_SHARED(Locks::mutator_lock_) {
2804 return
2805 // ClassNotFoundException.
2806 throwable->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
2807 class_linker))
2808 ||
2809 // NoClassDefFoundError. TODO: Reconsider this. b/130746382.
2810 throwable->InstanceOf(Runtime::Current()->GetPreAllocatedNoClassDefFoundError()->GetClass());
2811}
2812
2813// Clear exceptions caught in DexFile.defineClass.
2814ALWAYS_INLINE void FilterDexFileCaughtExceptions(Thread* self, ClassLinker* class_linker)
2815 REQUIRES_SHARED(Locks::mutator_lock_) {
2816 if (MatchesDexFileCaughtExceptions(self->GetException(), class_linker)) {
2817 self->ClearException();
2818 }
2819}
2820
2821} // namespace
2822
Calin Juravle415dc3d2017-06-28 11:03:12 -07002823// Finds the class in the boot class loader.
2824// If the class is found the method returns the resolved class. Otherwise it returns null.
2825ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2826 const char* descriptor,
2827 size_t hash) {
2828 ObjPtr<mirror::Class> result = nullptr;
2829 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2830 if (pair.second != nullptr) {
2831 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2832 if (klass != nullptr) {
2833 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002834 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002835 result = DefineClass(self,
2836 descriptor,
2837 hash,
2838 ScopedNullHandle<mirror::ClassLoader>(),
2839 *pair.first,
2840 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002841 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002842 if (result == nullptr) {
2843 CHECK(self->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002844 FilterDexFileCaughtExceptions(self, this);
Andreas Gampef865ea92015-04-13 22:14:19 -07002845 }
2846 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002847 return result;
2848}
Andreas Gampef865ea92015-04-13 22:14:19 -07002849
Calin Juravle415dc3d2017-06-28 11:03:12 -07002850ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2851 ScopedObjectAccessAlreadyRunnable& soa,
2852 const char* descriptor,
2853 size_t hash,
2854 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00002855 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2856 IsInMemoryDexClassLoader(soa, class_loader) ||
2857 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002858 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002859
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002860 ObjPtr<mirror::Class> ret;
2861 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002862 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002863 if (dex_class_def != nullptr) {
2864 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2865 descriptor,
2866 hash,
2867 class_loader,
2868 *cp_dex_file,
2869 *dex_class_def);
2870 if (klass == nullptr) {
2871 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002872 FilterDexFileCaughtExceptions(soa.Self(), this);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002873 // TODO: Is it really right to break here, and not check the other dex files?
Andreas Gampe501c3b02019-04-17 21:54:27 +00002874 } else {
2875 DCHECK(!soa.Self()->IsExceptionPending());
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002876 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002877 ret = klass;
2878 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002879 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002880 return true; // Continue with the next DexFile.
2881 };
2882
2883 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2884 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002885}
2886
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002887ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2888 const char* descriptor,
2889 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002890 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002891 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002892 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002893 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002894 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002895 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2896 // for primitive classes that aren't backed by dex files.
2897 return FindPrimitiveClass(descriptor[0]);
2898 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002899 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002900 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002901 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002902 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002903 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002904 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002905 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002906 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002907 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002908 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002909 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002910 return DefineClass(self,
2911 descriptor,
2912 hash,
2913 ScopedNullHandle<mirror::ClassLoader>(),
2914 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002915 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002916 } else {
2917 // The boot class loader is searched ahead of the application class loader, failures are
2918 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2919 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002920 ObjPtr<mirror::Throwable> pre_allocated =
2921 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002922 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002923 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002924 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002925 }
2926 ObjPtr<mirror::Class> result_ptr;
2927 bool descriptor_equals;
2928 if (descriptor[0] == '[') {
2929 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2930 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2931 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2932 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002933 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002934 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002935 bool known_hierarchy =
2936 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2937 if (result_ptr != nullptr) {
2938 // The chain was understood and we found the class. We still need to add the class to
2939 // the class table to protect from racy programs that can try and redefine the path list
2940 // which would change the Class<?> returned for subsequent evaluation of const-class.
2941 DCHECK(known_hierarchy);
2942 DCHECK(result_ptr->DescriptorEquals(descriptor));
2943 descriptor_equals = true;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002944 } else if (!self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002945 // Either the chain wasn't understood or the class wasn't found.
Andreas Gampe501c3b02019-04-17 21:54:27 +00002946 // If there is a pending exception we didn't clear, it is a not a ClassNotFoundException and
2947 // we should return it instead of silently clearing and retrying.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002948 //
2949 // If the chain was understood but we did not find the class, let the Java-side
2950 // rediscover all this and throw the exception with the right stack trace. Note that
2951 // the Java-side could still succeed for racy programs if another thread is actively
2952 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002953
Alex Light185a4612018-10-04 15:54:25 -07002954 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002955 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002956 // Oops, we can't call into java so we can't run actual class-loader code.
2957 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002958 ObjPtr<mirror::Throwable> pre_allocated =
2959 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2960 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002961 return nullptr;
2962 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002963
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002964 // Inlined DescriptorToDot(descriptor) with extra validation.
2965 //
2966 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2967 // the DescriptorEquals() check below and give a confusing error message. For example,
2968 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2969 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2970 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2971 size_t descriptor_length = strlen(descriptor);
2972 if (UNLIKELY(descriptor[0] != 'L') ||
2973 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2974 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2975 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2976 return nullptr;
2977 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002978
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002979 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2980 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
Mathieu Chartierd399f572019-04-17 12:34:19 -07002981 ScopedLocalRef<jobject> class_loader_object(
2982 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
2983 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2984 {
2985 ScopedThreadStateChange tsc(self, kNative);
2986 ScopedLocalRef<jobject> class_name_object(
2987 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2988 if (class_name_object.get() == nullptr) {
2989 DCHECK(self->IsExceptionPending()); // OOME.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002990 return nullptr;
2991 }
Mathieu Chartierd399f572019-04-17 12:34:19 -07002992 CHECK(class_loader_object.get() != nullptr);
2993 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2994 WellKnownClasses::java_lang_ClassLoader_loadClass,
2995 class_name_object.get()));
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002996 }
Mathieu Chartierd399f572019-04-17 12:34:19 -07002997 if (result.get() == nullptr && !self->IsExceptionPending()) {
2998 // broken loader - throw NPE to be compatible with Dalvik
2999 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
3000 class_name_string.c_str()).c_str());
3001 return nullptr;
3002 }
3003 result_ptr = soa.Decode<mirror::Class>(result.get());
3004 // Check the name of the returned class.
3005 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Andreas Gampe501c3b02019-04-17 21:54:27 +00003006 } else {
3007 DCHECK(!MatchesDexFileCaughtExceptions(self->GetException(), this));
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00003008 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003009 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003010
3011 if (self->IsExceptionPending()) {
3012 // If the ClassLoader threw or array class allocation failed, pass that exception up.
3013 // However, to comply with the RI behavior, first check if another thread succeeded.
3014 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
3015 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
3016 self->ClearException();
3017 return EnsureResolved(self, descriptor, result_ptr);
3018 }
3019 return nullptr;
3020 }
3021
3022 // Try to insert the class to the class table, checking for mismatch.
3023 ObjPtr<mirror::Class> old;
3024 {
3025 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3026 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
3027 old = class_table->Lookup(descriptor, hash);
3028 if (old == nullptr) {
3029 old = result_ptr; // For the comparison below, after releasing the lock.
3030 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01003031 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003032 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003033 } // else throw below, after releasing the lock.
3034 }
3035 }
3036 if (UNLIKELY(old != result_ptr)) {
3037 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
3038 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01003039 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00003040 const char* loader_class_name =
3041 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
3042 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
3043 << " is not well-behaved; it returned a different Class for racing loadClass(\""
3044 << DescriptorToDot(descriptor) << "\").";
3045 return EnsureResolved(self, descriptor, old);
3046 }
3047 if (UNLIKELY(!descriptor_equals)) {
3048 std::string result_storage;
3049 const char* result_name = result_ptr->GetDescriptor(&result_storage);
3050 std::string loader_storage;
3051 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
3052 ThrowNoClassDefFoundError(
3053 "Initiating class loader of type %s returned class %s instead of %s.",
3054 DescriptorToDot(loader_class_name).c_str(),
3055 DescriptorToDot(result_name).c_str(),
3056 DescriptorToDot(descriptor).c_str());
3057 return nullptr;
3058 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003059 // Success.
3060 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003061}
3062
Vladimir Markob9c29f62019-03-20 14:22:51 +00003063static bool IsReservedBootClassPathDescriptor(const char* descriptor) {
3064 std::string_view descriptor_sv(descriptor);
Vladimir Marko29885b32019-04-03 10:09:26 +01003065 return
3066 // Reserved conscrypt packages (includes sub-packages under these paths).
3067 StartsWith(descriptor_sv, "Landroid/net/ssl/") ||
3068 StartsWith(descriptor_sv, "Lcom/android/org/conscrypt/") ||
3069 // Reserved updatable-media package (includes sub-packages under this path).
3070 StartsWith(descriptor_sv, "Landroid/media/");
Vladimir Markob9c29f62019-03-20 14:22:51 +00003071}
3072
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003073ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3074 const char* descriptor,
3075 size_t hash,
3076 Handle<mirror::ClassLoader> class_loader,
3077 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003078 const dex::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003079 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003080 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003081
Brian Carlstromaded5f72011-10-07 17:15:04 -07003082 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003083 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003084 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003085 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003086 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003087 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003088 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003089 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003090 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003091 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003092 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003093 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003094 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003095 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003096 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003097 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003098 }
3099
Vladimir Markob9c29f62019-03-20 14:22:51 +00003100 // For AOT-compilation of an app, we may use a shortened boot class path that excludes
3101 // some runtime modules. Prevent definition of classes in app class loader that could clash
3102 // with these modules as these classes could be resolved differently during execution.
3103 if (class_loader != nullptr &&
3104 Runtime::Current()->IsAotCompiler() &&
3105 IsReservedBootClassPathDescriptor(descriptor)) {
3106 ObjPtr<mirror::Throwable> pre_allocated =
3107 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3108 self->SetException(pre_allocated);
3109 return nullptr;
3110 }
3111
Alex Lighte9f61032018-09-24 16:04:51 -07003112 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3113 // code to be executed. We put it up here so we can avoid all the allocations associated with
3114 // creating the class. This can happen with (eg) jit threads.
3115 if (!self->CanLoadClasses()) {
3116 // Make sure we don't try to load anything, potentially causing an infinite loop.
3117 ObjPtr<mirror::Throwable> pre_allocated =
3118 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3119 self->SetException(pre_allocated);
3120 return nullptr;
3121 }
3122
Andreas Gampefa4333d2017-02-14 11:10:34 -08003123 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003124 // Allocate a class with the status of not ready.
3125 // Interface object should get the right size here. Regular class will
3126 // figure out the right size later and be replaced with one of the right
3127 // size when the class becomes resolved.
Nicolas Geoffrayabadf022017-08-03 08:25:41 +00003128 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003129 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003130 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003131 self->AssertPendingOOMException();
Ian Rogersc114b5f2014-07-21 08:55:01 -07003132 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003133 }
Alex Lightb0f11922017-01-23 14:25:17 -08003134 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3135 // nothing.
3136 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003137 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003138 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3139 // will only be called once.
3140 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3141 klass,
3142 class_loader,
3143 dex_file,
3144 dex_class_def,
3145 &new_dex_file,
3146 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003147 // Check to see if an exception happened during runtime callbacks. Return if so.
3148 if (self->IsExceptionPending()) {
3149 return nullptr;
3150 }
Alex Lightb0f11922017-01-23 14:25:17 -08003151 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003152 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003153 self->AssertPendingException();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003154 return nullptr;
3155 }
3156 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003157 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003158
Jeff Hao848f70a2014-01-15 13:49:50 -08003159 // Mark the string class by setting its access flag.
3160 if (UNLIKELY(!init_done_)) {
3161 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3162 klass->SetStringClass();
3163 }
3164 }
3165
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003166 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003167 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003168 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003169 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003170
Mathieu Chartier590fee92013-09-13 13:46:47 -07003171 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003172 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003173 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003174 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3175 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003176 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003177 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003178
Mathieu Chartierc7853442015-03-27 14:35:38 -07003179 // Load the fields and other things after we are inserted in the table. This is so that we don't
3180 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3181 // other reason is that the field roots are only visited from the class table. So we need to be
3182 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003183 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003184 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003185 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003186 // An exception occured during load, set status to erroneous while holding klass' lock in case
3187 // notification is necessary.
3188 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003189 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003190 }
3191 return nullptr;
3192 }
3193
Brian Carlstromaded5f72011-10-07 17:15:04 -07003194 // Finish loading (if necessary) by finding parents
3195 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003196 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003197 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003198 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003199 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003200 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003201 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003202 }
3203 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003204
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003205 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003206 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003207 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003208
Brian Carlstromaded5f72011-10-07 17:15:04 -07003209 // Link the class (if necessary)
3210 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003211 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003212 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003213
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003214 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003215 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003216 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003217 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003218 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003219 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07003220 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003221 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003222 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003223 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003224 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003225
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003226 // Instrumentation may have updated entrypoints for all methods of all
3227 // classes. However it could not update methods of this class while we
3228 // were loading it. Now the class is resolved, we can update entrypoints
3229 // as required by instrumentation.
3230 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3231 // We must be in the kRunnable state to prevent instrumentation from
3232 // suspending all threads to update entrypoints while we are doing it
3233 // for this class.
3234 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003235 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003236 }
3237
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003238 /*
3239 * We send CLASS_PREPARE events to the debugger from here. The
3240 * definition of "preparation" is creating the static fields for a
3241 * class and initializing them to the standard default values, but not
3242 * executing any code (that comes later, during "initialization").
3243 *
3244 * We did the static preparation in LinkClass.
3245 *
3246 * The class has been prepared and resolved but possibly not yet verified
3247 * at this point.
3248 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003249 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003250
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003251 // Notify native debugger of the new class and its layout.
3252 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3253
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003254 return h_new_class.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003255}
3256
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003257uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003258 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003259 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003260 size_t num_8 = 0;
3261 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003262 size_t num_32 = 0;
3263 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003264 ClassAccessor accessor(dex_file, dex_class_def);
3265 // We allow duplicate definitions of the same field in a class_data_item
3266 // but ignore the repeated indexes here, b/21868015.
3267 uint32_t last_field_idx = dex::kDexNoIndex;
3268 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3269 uint32_t field_idx = field.GetIndex();
3270 // Ordering enforced by DexFileVerifier.
3271 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3272 if (UNLIKELY(field_idx == last_field_idx)) {
3273 continue;
3274 }
3275 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003276 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003277 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3278 char c = descriptor[0];
3279 switch (c) {
3280 case 'L':
3281 case '[':
3282 num_ref++;
3283 break;
3284 case 'J':
3285 case 'D':
3286 num_64++;
3287 break;
3288 case 'I':
3289 case 'F':
3290 num_32++;
3291 break;
3292 case 'S':
3293 case 'C':
3294 num_16++;
3295 break;
3296 case 'B':
3297 case 'Z':
3298 num_8++;
3299 break;
3300 default:
3301 LOG(FATAL) << "Unknown descriptor: " << c;
3302 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003303 }
3304 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003305 return mirror::Class::ComputeClassSize(false,
3306 0,
3307 num_8,
3308 num_16,
3309 num_32,
3310 num_64,
3311 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003312 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003313}
3314
Alex Lightfc49fec2018-01-16 22:28:36 +00003315// Special case to get oat code without overwriting a trampoline.
3316const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003317 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003318 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003319 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003320 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003321 auto* code = method->GetOatMethodQuickCode(GetImagePointerSize());
3322 if (code != nullptr) {
3323 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003324 }
Alex Lightfc49fec2018-01-16 22:28:36 +00003325 if (method->IsNative()) {
3326 // No code and native? Use generic trampoline.
3327 return GetQuickGenericJniStub();
3328 }
3329 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003330}
3331
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003332bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003333 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003334 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3335 return false;
3336 }
3337
Elliott Hughes956af0f2014-12-11 14:34:28 -08003338 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003339 return true;
3340 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003341
3342 Runtime* runtime = Runtime::Current();
3343 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3344 if (instr->InterpretOnly()) {
3345 return true;
3346 }
3347
3348 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3349 // Doing this check avoids doing compiled/interpreter transitions.
3350 return true;
3351 }
3352
Alex Light3dacdd62019-03-12 15:45:47 +00003353 if (Thread::Current()->IsForceInterpreter() ||
3354 Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003355 // Force the use of interpreter when it is required by the debugger.
3356 return true;
3357 }
3358
Alex Light8f34aba2017-10-09 13:46:32 -07003359 if (Thread::Current()->IsAsyncExceptionPending()) {
3360 // Force use of interpreter to handle async-exceptions
3361 return true;
3362 }
3363
Alex Light2d441b12018-06-08 15:33:21 -07003364 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3365 const void* instr_target = instr->GetCodeForInvoke(method);
3366 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3367 return ShouldUseInterpreterEntrypoint(method, instr_target);
3368 }
3369
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003370 if (runtime->IsJavaDebuggable()) {
3371 // For simplicity, we ignore precompiled code and go to the interpreter
3372 // assuming we don't already have jitted code.
3373 // We could look at the oat file where `quick_code` is being defined,
3374 // and check whether it's been compiled debuggable, but we decided to
3375 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003376 jit::Jit* jit = Runtime::Current()->GetJit();
3377 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3378 }
3379
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003380 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003381 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003382 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003383 // since we want to JIT it (at first use) with extra stackmaps for native
3384 // debugging. We keep however all AOT code from the boot image,
3385 // since the JIT-at-first-use is blocking and would result in non-negligible
3386 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003387 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003388 }
3389
3390 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003391}
3392
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003393void ClassLinker::FixupStaticTrampolines(ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003394 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
David Sehr709b0702016-10-13 09:12:37 -07003395 DCHECK(klass->IsInitialized()) << klass->PrettyDescriptor();
Ian Rogers1c829822013-09-30 18:18:50 -07003396 if (klass->NumDirectMethods() == 0) {
3397 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003398 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003399 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003400 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003401 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003402 return; // OAT file unavailable.
3403 }
Ian Rogers19846512012-02-24 11:42:47 -08003404 }
Alex Light64ad14d2014-08-19 14:23:13 -07003405
Mathieu Chartierf8322842014-05-16 10:59:25 -07003406 const DexFile& dex_file = klass->GetDexFile();
Mathieu Chartier18e26872018-06-04 17:19:02 -07003407 const uint16_t class_def_idx = klass->GetDexClassDefIndex();
3408 CHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
3409 ClassAccessor accessor(dex_file, class_def_idx);
Ian Rogers1c829822013-09-30 18:18:50 -07003410 // There should always be class data if there were direct methods.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003411 CHECK(accessor.HasClassData()) << klass->PrettyDescriptor();
Ian Rogers97b52f82014-08-14 11:34:07 -07003412 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003413 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3414 klass->GetDexClassDefIndex(),
3415 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003416 // Link the code of methods skipped by LinkCode.
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003417 for (size_t method_index = 0; method_index < accessor.NumDirectMethods(); ++method_index) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003418 ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003419 if (!method->IsStatic()) {
3420 // Only update static methods.
3421 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003422 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003423 const void* quick_code = nullptr;
3424 if (has_oat_class) {
3425 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003426 quick_code = oat_method.GetQuickCode();
3427 }
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01003428 // Check if we have JIT compiled code for it.
3429 if (quick_code == nullptr && Runtime::Current()->GetJit() != nullptr) {
3430 quick_code = Runtime::Current()->GetJit()->GetCodeCache()->GetZygoteSavedEntryPoint(method);
3431 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003432 // Check whether the method is native, in which case it's generic JNI.
3433 if (quick_code == nullptr && method->IsNative()) {
3434 quick_code = GetQuickGenericJniStub();
3435 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003436 // Use interpreter entry point.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003437 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003438 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08003439 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003440 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003441 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003442}
3443
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003444// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3445// method. Should only be called on non-invokable methods.
3446inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method) {
Alex Light9139e002015-10-09 15:59:48 -07003447 DCHECK(method != nullptr);
3448 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003449 method->SetEntryPointFromQuickCompiledCodePtrSize(
3450 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3451 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003452}
3453
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003454static void LinkCode(ClassLinker* class_linker,
3455 ArtMethod* method,
3456 const OatFile::OatClass* oat_class,
3457 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003458 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003459 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003460 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003461 // The following code only applies to a non-compiler runtime.
3462 return;
3463 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003464 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003465 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003466 if (oat_class != nullptr) {
3467 // Every kind of method should at least get an invoke stub from the oat_method.
3468 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07003469 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003470 oat_method.LinkMethod(method);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003471 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003472
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003473 // Install entry point from interpreter.
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003474 const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003475 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
Jeff Hao16743632013-05-08 10:59:04 -07003476
Alex Light9139e002015-10-09 15:59:48 -07003477 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003478 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003479 return;
3480 }
Ian Rogers19846512012-02-24 11:42:47 -08003481
3482 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003483 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003484 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3485 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003486 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003487 } else if (quick_code == nullptr && method->IsNative()) {
3488 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Tamas Berghammer3a98aae2016-02-08 20:21:54 +00003489 } else if (enter_interpreter) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003490 // Set entry point from compiled code if there's no code or in interpreter only mode.
3491 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08003492 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003493
Ian Rogers62d6c772013-02-27 08:32:07 -08003494 if (method->IsNative()) {
3495 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003496 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07003497
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003498 if (enter_interpreter || quick_code == nullptr) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003499 // We have a native method here without code. Then it should have either the generic JNI
3500 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
3501 // TODO: this doesn't handle all the cases where trampolines may be installed.
3502 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003503 DCHECK(class_linker->IsQuickGenericJniStub(entry_point) ||
3504 class_linker->IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07003505 }
Nicolas Geoffray5a0622a2019-04-12 16:35:17 +01003506
3507 // For the jitzygote configuration we want JNI stubs to be compiled, just like boot classpath
3508 // AOT where we compile all native entries.
3509 if (!Runtime::Current()->IsUsingDefaultBootImageLocation() &&
3510 method->GetDeclaringClass()->GetClassLoader() == nullptr &&
David Srbeckyd94c87d2019-04-16 18:40:03 +01003511 method->GetDeclaringClass()->IsResolved() &&
Nicolas Geoffray5a0622a2019-04-12 16:35:17 +01003512 Runtime::Current()->GetJit() != nullptr) {
3513 Runtime::Current()->GetJit()->CompileMethod(
3514 method, Thread::Current(), /* baseline= */ false, /* osr= */ false);
3515 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003516 }
3517}
3518
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003519void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003520 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003521 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003522 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003523 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003524 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003525 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003526 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003527 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003528
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003529 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003530 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003531 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003532 klass->SetAccessFlags(access_flags);
3533 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003534 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003535 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003536
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003537 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003538 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003539}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003540
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003541LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3542 LinearAlloc* allocator,
3543 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003544 if (length == 0) {
3545 return nullptr;
3546 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003547 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3548 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3549 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003550 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003551 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003552 CHECK(ret != nullptr);
3553 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3554 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003555}
3556
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003557LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3558 LinearAlloc* allocator,
3559 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003560 if (length == 0) {
3561 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003562 }
Vladimir Marko14632852015-08-17 12:07:23 +01003563 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3564 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003565 const size_t storage_size =
3566 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003567 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003568 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003569 CHECK(ret != nullptr);
3570 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003571 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003572 }
3573 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003574}
3575
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003576LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003577 if (class_loader == nullptr) {
3578 return Runtime::Current()->GetLinearAlloc();
3579 }
3580 LinearAlloc* allocator = class_loader->GetAllocator();
3581 DCHECK(allocator != nullptr);
3582 return allocator;
3583}
3584
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003585LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003586 if (class_loader == nullptr) {
3587 return Runtime::Current()->GetLinearAlloc();
3588 }
3589 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3590 LinearAlloc* allocator = class_loader->GetAllocator();
3591 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003592 RegisterClassLoader(class_loader);
3593 allocator = class_loader->GetAllocator();
3594 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003595 }
3596 return allocator;
3597}
3598
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003599void ClassLinker::LoadClass(Thread* self,
3600 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003601 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003602 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003603 ClassAccessor accessor(dex_file,
3604 dex_class_def,
3605 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003606 if (!accessor.HasClassData()) {
3607 return;
3608 }
3609 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003610 {
3611 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3612 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003613 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003614 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003615 // We allow duplicate definitions of the same field in a class_data_item
3616 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003617 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003618 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3619 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003620 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003621 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3622 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003623 accessor.NumInstanceFields());
3624 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003625 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003626 uint32_t last_static_field_idx = 0u;
3627 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003628
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003629 // Methods
3630 bool has_oat_class = false;
3631 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3632 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3633 : OatFile::OatClass::Invalid();
3634 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3635 klass->SetMethodsPtr(
3636 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3637 accessor.NumDirectMethods(),
3638 accessor.NumVirtualMethods());
3639 size_t class_def_method_index = 0;
3640 uint32_t last_dex_method_index = dex::kDexNoIndex;
3641 size_t last_class_def_method_index = 0;
3642
3643 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3644 // methods needs to decode all of the fields.
3645 accessor.VisitFieldsAndMethods([&](
3646 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3647 uint32_t field_idx = field.GetIndex();
3648 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3649 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3650 LoadField(field, klass, &sfields->At(num_sfields));
3651 ++num_sfields;
3652 last_static_field_idx = field_idx;
3653 }
3654 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3655 uint32_t field_idx = field.GetIndex();
3656 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3657 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3658 LoadField(field, klass, &ifields->At(num_ifields));
3659 ++num_ifields;
3660 last_instance_field_idx = field_idx;
3661 }
3662 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3663 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3664 image_pointer_size_);
3665 LoadMethod(dex_file, method, klass, art_method);
3666 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3667 uint32_t it_method_index = method.GetIndex();
3668 if (last_dex_method_index == it_method_index) {
3669 // duplicate case
3670 art_method->SetMethodIndex(last_class_def_method_index);
3671 } else {
3672 art_method->SetMethodIndex(class_def_method_index);
3673 last_dex_method_index = it_method_index;
3674 last_class_def_method_index = class_def_method_index;
3675 }
3676 ++class_def_method_index;
3677 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3678 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3679 class_def_method_index - accessor.NumDirectMethods(),
3680 image_pointer_size_);
3681 LoadMethod(dex_file, method, klass, art_method);
3682 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3683 ++class_def_method_index;
3684 });
3685
3686 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003687 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003688 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3689 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3690 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003691 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3692 if (sfields != nullptr) {
3693 sfields->SetSize(num_sfields);
3694 }
3695 if (ifields != nullptr) {
3696 ifields->SetSize(num_ifields);
3697 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003698 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003699 // Set the field arrays.
3700 klass->SetSFieldsPtr(sfields);
3701 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003702 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003703 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003704 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003705 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003706 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003707 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003708}
3709
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003710void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003711 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003712 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003713 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003714 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003715 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003716
David Brazdil85865692018-10-30 17:26:20 +00003717 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3718 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003719}
3720
Mathieu Chartier268764d2016-09-13 12:09:38 -07003721void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003722 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003723 Handle<mirror::Class> klass,
3724 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003725 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003726 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003727 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003728
Mathieu Chartier268764d2016-09-13 12:09:38 -07003729 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003730 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003731 dst->SetDeclaringClass(klass.Get());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003732 dst->SetCodeItemOffset(method.GetCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003733
David Brazdil85865692018-10-30 17:26:20 +00003734 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3735 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003736
Ian Rogersdfb325e2013-10-30 01:00:44 -07003737 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003738 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003739 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3740 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003741 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003742 klass->SetFinalizable();
3743 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003744 std::string temp;
3745 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003746 // The Enum class declares a "final" finalize() method to prevent subclasses from
3747 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3748 // subclasses, so we exclude it here.
3749 // We also want to avoid setting the flag on Object, where we know that finalize() is
3750 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003751 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3752 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003753 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003754 }
3755 }
3756 }
3757 } else if (method_name[0] == '<') {
3758 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003759 bool is_init = (strcmp("<init>", method_name) == 0);
3760 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003761 if (UNLIKELY(!is_init && !is_clinit)) {
3762 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3763 } else {
3764 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3765 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003766 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003767 access_flags |= kAccConstructor;
3768 }
3769 }
3770 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003771 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3772 // Check if the native method is annotated with @FastNative or @CriticalNative.
3773 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3774 dex_file, dst->GetClassDef(), dex_method_idx);
3775 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003776 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003777 // Must be done after SetAccessFlags since IsAbstract depends on it.
3778 if (klass->IsInterface() && dst->IsAbstract()) {
3779 dst->CalculateAndSetImtIndex();
3780 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003781}
3782
Ian Rogers7b078e82014-09-10 14:44:24 -07003783void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003784 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003785 self,
3786 dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003787 Runtime::Current()->GetLinearAlloc());
3788 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003789 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003790}
3791
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003792void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003793 ObjPtr<mirror::DexCache> dex_cache) {
3794 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003795 boot_class_path_.push_back(&dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003796 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003797 RegisterDexFileLocked(dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003798}
3799
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003800void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003801 ObjPtr<mirror::DexCache> dex_cache,
3802 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003803 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003804 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003805 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003806 // For app images, the dex cache location may be a suffix of the dex file location since the
3807 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003808 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3809 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003810 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3811 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003812 // The following paths checks don't work on preopt when using boot dex files, where the dex
3813 // cache location is the one on device, and the dex_file's location is the one on host.
3814 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3815 CHECK_GE(dex_file_location.length(), dex_cache_length)
3816 << dex_cache_location << " " << dex_file.GetLocation();
3817 const std::string dex_file_suffix = dex_file_location.substr(
3818 dex_file_location.length() - dex_cache_length,
3819 dex_cache_length);
3820 // Example dex_cache location is SettingsProvider.apk and
3821 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3822 CHECK_EQ(dex_cache_location, dex_file_suffix);
3823 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003824 const OatFile* oat_file =
3825 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003826 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3827 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3828 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3829 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003830 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003831 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3832 DexCacheData data = *it;
3833 if (self->IsJWeakCleared(data.weak_root)) {
3834 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003835 it = dex_caches_.erase(it);
3836 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003837 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003838 it->dex_file->GetOatDexFile() != nullptr &&
3839 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003840 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003841 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003842 ++it;
3843 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003844 }
Vladimir Markob066d432018-01-03 13:14:37 +00003845 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003846 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003847 }
David Brazdila5c3a802019-03-08 14:59:41 +00003848 // Let hiddenapi assign a domain to the newly registered dex file.
3849 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
3850
Vladimir Markocd556b02017-02-03 11:47:34 +00003851 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003852 dex_cache->SetDexFile(&dex_file);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003853 DexCacheData data;
3854 data.weak_root = dex_cache_jweak;
3855 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003856 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003857 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003858 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003859 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3860 // path dex caches without an image.
3861 data.class_table->InsertStrongRoot(dex_cache);
3862 if (class_loader != nullptr) {
3863 // Since we added a strong root to the class table, do the write barrier as required for
3864 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003865 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003866 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003867 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003868}
3869
Vladimir Markocd556b02017-02-03 11:47:34 +00003870ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCache(Thread* self, const DexCacheData& data) {
3871 return data.IsValid()
3872 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root))
3873 : nullptr;
3874}
3875
3876ObjPtr<mirror::DexCache> ClassLinker::EnsureSameClassLoader(
3877 Thread* self,
3878 ObjPtr<mirror::DexCache> dex_cache,
3879 const DexCacheData& data,
3880 ObjPtr<mirror::ClassLoader> class_loader) {
3881 DCHECK_EQ(dex_cache->GetDexFile(), data.dex_file);
3882 if (data.class_table != ClassTableForClassLoader(class_loader)) {
3883 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
3884 "Attempt to register dex file %s with multiple class loaders",
3885 data.dex_file->GetLocation().c_str());
3886 return nullptr;
3887 }
3888 return dex_cache;
3889}
3890
Alex Light07f06212017-06-01 14:01:43 -07003891void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3892 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003893 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003894 Thread* self = Thread::Current();
3895 StackHandleScope<2> hs(self);
3896 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3897 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3898 const DexFile* dex_file = dex_cache->GetDexFile();
3899 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3900 if (kIsDebugBuild) {
3901 DexCacheData old_data;
3902 {
3903 ReaderMutexLock mu(self, *Locks::dex_lock_);
3904 old_data = FindDexCacheDataLocked(*dex_file);
3905 }
3906 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3907 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3908 << "been registered on dex file " << dex_file->GetLocation();
3909 }
3910 ClassTable* table;
3911 {
3912 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3913 table = InsertClassTableForClassLoader(h_class_loader.Get());
3914 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003915 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3916 // a thread holding the dex lock and blocking on a condition variable regarding
3917 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003918 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003919 WriterMutexLock mu(self, *Locks::dex_lock_);
3920 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3921 table->InsertStrongRoot(h_dex_cache.Get());
3922 if (h_class_loader.Get() != nullptr) {
3923 // Since we added a strong root to the class table, do the write barrier as required for
3924 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003925 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003926 }
3927}
3928
Vladimir Markocd556b02017-02-03 11:47:34 +00003929ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3930 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003931 Thread* self = Thread::Current();
Vladimir Markocd556b02017-02-03 11:47:34 +00003932 DexCacheData old_data;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003933 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003934 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003935 old_data = FindDexCacheDataLocked(dex_file);
3936 }
3937 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCache(self, old_data);
3938 if (old_dex_cache != nullptr) {
3939 return EnsureSameClassLoader(self, old_dex_cache, old_data, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003940 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003941 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003942 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3943 DCHECK(linear_alloc != nullptr);
3944 ClassTable* table;
3945 {
3946 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3947 table = InsertClassTableForClassLoader(class_loader);
3948 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003949 // Don't alloc while holding the lock, since allocation may need to
3950 // suspend all threads and another thread may need the dex_lock_ to
3951 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00003952 StackHandleScope<3> hs(self);
3953 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003954 ObjPtr<mirror::String> location;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07003955 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(/*out*/&location,
3956 self,
3957 dex_file)));
3958 Handle<mirror::String> h_location(hs.NewHandle(location));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003959 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003960 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3961 // a thread holding the dex lock and blocking on a condition variable regarding
3962 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003963 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08003964 WriterMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00003965 old_data = FindDexCacheDataLocked(dex_file);
3966 old_dex_cache = DecodeDexCache(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08003967 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003968 // Do InitializeDexCache while holding dex lock to make sure two threads don't call it at the
3969 // same time with the same dex cache. Since the .bss is shared this can cause failing DCHECK
3970 // that the arrays are null.
3971 mirror::DexCache::InitializeDexCache(self,
3972 h_dex_cache.Get(),
3973 h_location.Get(),
3974 &dex_file,
3975 linear_alloc,
3976 image_pointer_size_);
3977 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003978 }
Vladimir Markocd556b02017-02-03 11:47:34 +00003979 }
3980 if (old_dex_cache != nullptr) {
3981 // Another thread managed to initialize the dex cache faster, so use that DexCache.
3982 // If this thread encountered OOME, ignore it.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003983 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
Vladimir Markocd556b02017-02-03 11:47:34 +00003984 self->ClearException();
3985 // We cannot call EnsureSameClassLoader() while holding the dex_lock_.
3986 return EnsureSameClassLoader(self, old_dex_cache, old_data, h_class_loader.Get());
3987 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003988 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003989 self->AssertPendingOOMException();
3990 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003991 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07003992 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003993 if (h_class_loader.Get() != nullptr) {
3994 // Since we added a strong root to the class table, do the write barrier as required for
3995 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003996 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08003997 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003998 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07003999}
4000
Vladimir Markocd556b02017-02-03 11:47:34 +00004001bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004002 ReaderMutexLock mu(self, *Locks::dex_lock_);
Vladimir Markocd556b02017-02-03 11:47:34 +00004003 return DecodeDexCache(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004004}
4005
Vladimir Markocd556b02017-02-03 11:47:34 +00004006ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
4007 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004008 DexCacheData dex_cache_data = FindDexCacheDataLocked(dex_file);
4009 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCache(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004010 if (dex_cache != nullptr) {
4011 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004012 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004013 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004014 for (const DexCacheData& data : dex_caches_) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004015 if (DecodeDexCache(self, data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07004016 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004017 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004018 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004019 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
4020 << " " << &dex_file << " " << dex_cache_data.dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08004021 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004022}
4023
Vladimir Markocd556b02017-02-03 11:47:34 +00004024ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
4025 const DexFile* dex_file = dex_cache->GetDexFile();
4026 DCHECK(dex_file != nullptr);
4027 ReaderMutexLock mu(self, *Locks::dex_lock_);
4028 // Search assuming unique-ness of dex file.
4029 for (const DexCacheData& data : dex_caches_) {
4030 // Avoid decoding (and read barriers) other unrelated dex caches.
4031 if (data.dex_file == dex_file) {
4032 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCache(self, data);
4033 if (registered_dex_cache != nullptr) {
4034 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
4035 return data.class_table;
4036 }
4037 }
4038 }
4039 return nullptr;
4040}
4041
4042ClassLinker::DexCacheData ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
4043 // Search assuming unique-ness of dex file.
4044 for (const DexCacheData& data : dex_caches_) {
4045 // Avoid decoding (and read barriers) other unrelated dex caches.
4046 if (data.dex_file == &dex_file) {
4047 return data;
4048 }
4049 }
4050 return DexCacheData();
4051}
4052
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004053ObjPtr<mirror::Class> ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004054 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004055 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Markoacb906d2018-05-30 10:23:49 +01004056 if (UNLIKELY(primitive_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004057 self->AssertPendingOOMException();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004058 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004059 }
Ian Rogers1f539342012-10-03 21:09:42 -07004060 // Must hold lock on object when initializing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004061 StackHandleScope<1> hs(self);
4062 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004063 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004064 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
4065 h_class->SetPrimitiveType(type);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004066 h_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Andreas Gampe5b20b352018-10-11 19:03:20 -07004067 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(h_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004068 mirror::Class::SetStatus(h_class, ClassStatus::kInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004069 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004070 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
4071 h_class.Get(),
4072 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004073 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004074 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07004075}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004076
Vladimir Marko02610552018-06-04 14:38:00 +01004077inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4078 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4079}
4080
Brian Carlstrombe977852011-07-19 14:54:54 -07004081// Create an array class (i.e. the class object for the array, not the
4082// array itself). "descriptor" looks like "[C" or "[[[[B" or
4083// "[Ljava/lang/String;".
4084//
4085// If "descriptor" refers to an array of primitives, look up the
4086// primitive type's internally-generated class object.
4087//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004088// "class_loader" is the class loader of the class that's referring to
4089// us. It's used to ensure that we're looking for the element type in
4090// the right context. It does NOT become the class loader for the
4091// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004092//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004093// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004094ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4095 const char* descriptor,
4096 size_t hash,
4097 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004098 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004099 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004100 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004101
4102 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4103 // code to be executed. We put it up here so we can avoid all the allocations associated with
4104 // creating the class. This can happen with (eg) jit threads.
4105 if (!self->CanLoadClasses()) {
4106 // Make sure we don't try to load anything, potentially causing an infinite loop.
4107 ObjPtr<mirror::Throwable> pre_allocated =
4108 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4109 self->SetException(pre_allocated);
4110 return nullptr;
4111 }
4112
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004113 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4114 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004115 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004116 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004117 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004118 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4119 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004120 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004121 DCHECK(self->IsExceptionPending());
4122 return nullptr;
4123 } else {
4124 self->ClearException();
4125 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004126 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004127 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4128 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4129 return nullptr;
4130 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004131 // See if the component type is already loaded. Array classes are
4132 // always associated with the class loader of their underlying
4133 // element type -- an array of Strings goes with the loader for
4134 // java/lang/String -- so we need to look for it there. (The
4135 // caller should have checked for the existence of the class
4136 // before calling here, but they did so with *their* class loader,
4137 // not the component type's loader.)
4138 //
4139 // If we find it, the caller adds "loader" to the class' initiating
4140 // loader list, which should prevent us from going through this again.
4141 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004142 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004143 // are the same, because our caller (FindClass) just did the
4144 // lookup. (Even if we get this wrong we still have correct behavior,
4145 // because we effectively do this lookup again when we add the new
4146 // class to the hash table --- necessary because of possible races with
4147 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004148 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004149 ObjPtr<mirror::Class> new_class =
4150 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004151 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004152 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004153 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004154 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004155
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004156 // Fill out the fields in the Class.
4157 //
4158 // It is possible to execute some methods against arrays, because
4159 // all arrays are subclasses of java_lang_Object_, so we need to set
4160 // up a vtable. We can just point at the one in java_lang_Object_.
4161 //
4162 // Array classes are simple enough that we don't need to do a full
4163 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004164 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004165 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004166 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004167 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004168 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Class>>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004169 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004170 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::Object>>(this));
4171 } else if (strcmp(descriptor, "[Ljava/lang/String;") == 0) {
4172 new_class.Assign(GetClassRoot<mirror::ObjectArray<mirror::String>>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004173 } else if (strcmp(descriptor, "[Z") == 0) {
4174 new_class.Assign(GetClassRoot<mirror::BooleanArray>(this));
4175 } else if (strcmp(descriptor, "[B") == 0) {
4176 new_class.Assign(GetClassRoot<mirror::ByteArray>(this));
4177 } else if (strcmp(descriptor, "[C") == 0) {
4178 new_class.Assign(GetClassRoot<mirror::CharArray>(this));
4179 } else if (strcmp(descriptor, "[S") == 0) {
4180 new_class.Assign(GetClassRoot<mirror::ShortArray>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004181 } else if (strcmp(descriptor, "[I") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004182 new_class.Assign(GetClassRoot<mirror::IntArray>(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07004183 } else if (strcmp(descriptor, "[J") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004184 new_class.Assign(GetClassRoot<mirror::LongArray>(this));
Roland Levillain0e840272018-08-23 19:55:30 +01004185 } else if (strcmp(descriptor, "[F") == 0) {
4186 new_class.Assign(GetClassRoot<mirror::FloatArray>(this));
4187 } else if (strcmp(descriptor, "[D") == 0) {
4188 new_class.Assign(GetClassRoot<mirror::DoubleArray>(this));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004189 }
4190 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004191 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004192 new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004193 if (new_class == nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004194 self->AssertPendingOOMException();
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004195 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004196 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004197 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004198 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004199 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004200 DCHECK(new_class->GetComponentType() != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004201 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004202 new_class->SetSuperClass(java_lang_Object);
4203 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004204 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004205 new_class->SetClassLoader(component_type->GetClassLoader());
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07004206 if (component_type->IsPrimitive()) {
4207 new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
4208 } else {
4209 new_class->SetClassFlags(mirror::kClassFlagObjectArray);
4210 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004211 mirror::Class::SetStatus(new_class, ClassStatus::kLoaded, self);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00004212 new_class->PopulateEmbeddedVTable(image_pointer_size_);
4213 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
4214 new_class->SetImt(object_imt, image_pointer_size_);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004215 EnsureSkipAccessChecksMethods</* kNeedsVerified= */ true>(new_class, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004216 mirror::Class::SetStatus(new_class, ClassStatus::kInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004217 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07004218 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004219
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004220 // All arrays have java/lang/Cloneable and java/io/Serializable as
4221 // interfaces. We need to set that up here, so that stuff like
4222 // "instanceof" works right.
4223 //
4224 // Note: The GC could run during the call to FindSystemClass,
4225 // so we need to make sure the class object is GC-valid while we're in
4226 // there. Do this by clearing the interface list so the GC will just
4227 // think that the entries are null.
4228
4229
4230 // Use the single, global copies of "interfaces" and "iftable"
4231 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004232 {
Vladimir Marko02610552018-06-04 14:38:00 +01004233 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004234 CHECK(array_iftable != nullptr);
4235 new_class->SetIfTable(array_iftable);
4236 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004237
Elliott Hughes00626c22013-06-14 15:04:14 -07004238 // Inherit access flags from the component type.
4239 int access_flags = new_class->GetComponentType()->GetAccessFlags();
4240 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
4241 access_flags &= kAccJavaFlagsMask;
4242 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004243 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07004244 access_flags |= kAccAbstract | kAccFinal;
4245 access_flags &= ~kAccInterface;
Andreas Gampe5b20b352018-10-11 19:03:20 -07004246 // Arrays are access-checks-clean and preverified.
4247 access_flags |= kAccVerificationAttempted;
Elliott Hughes00626c22013-06-14 15:04:14 -07004248
4249 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004250
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004251 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004252 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004253 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4254 // duplicate events in case of races. Array classes don't really follow dedicated
4255 // load and prepare, anyways.
4256 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4257 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4258
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004259 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004260 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004261 }
4262 // Another thread must have loaded the class after we
4263 // started but before we finished. Abandon what we've
4264 // done.
4265 //
4266 // (Yes, this happens.)
4267
Vladimir Markobcf17522018-06-01 13:14:32 +01004268 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004269}
4270
Vladimir Marko9186b182018-11-06 14:55:54 +00004271ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4272 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004273 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004274 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4275 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4276 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4277 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4278 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4279 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4280 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4281 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4282 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004283 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004284 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004285 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004286 return GetClassRoot(class_root, this);
4287}
4288
4289ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4290 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4291 if (UNLIKELY(result == nullptr)) {
4292 std::string printable_type(PrintableChar(type));
4293 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4294 }
4295 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004296}
4297
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004298ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4299 ObjPtr<mirror::Class> klass,
4300 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004301 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004302 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004303 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004304 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004305 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004306 source += " from ";
4307 source += dex_cache->GetLocation()->ToModifiedUtf8();
4308 }
4309 LOG(INFO) << "Loaded class " << descriptor << source;
4310 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004311 {
4312 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004313 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004314 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004315 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004316 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004317 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004318 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004319 VerifyObject(klass);
4320 class_table->InsertWithHash(klass, hash);
4321 if (class_loader != nullptr) {
4322 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004323 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004324 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004325 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004326 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004327 }
4328 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004329 if (kIsDebugBuild) {
4330 // Test that copied methods correctly can find their holder.
4331 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4332 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4333 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004334 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004335 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004336}
4337
Vladimir Marko1998cd02017-01-13 13:02:58 +00004338void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004339 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4340 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4341 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4342 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004343 }
4344}
4345
Alex Lighte64300b2015-12-15 15:02:47 -08004346// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004347void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004348 LengthPrefixedArray<ArtMethod>* new_methods) {
4349 klass->SetMethodsPtrUnchecked(new_methods,
4350 klass->NumDirectMethods(),
4351 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004352 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004353 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004354}
4355
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004356ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4357 const char* descriptor,
4358 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004359 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4360}
4361
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004362ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4363 const char* descriptor,
4364 size_t hash,
4365 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004366 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4367 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4368 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004369 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004370 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004371 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004372 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004373 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004374 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004375}
4376
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004377class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4378 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004379 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004380
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004381 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004382 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004383 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004384 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004385 if (class_table != nullptr) {
4386 class_table->FreezeSnapshot();
4387 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004388 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004389};
4390
4391void ClassLinker::MoveClassTableToPreZygote() {
4392 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004393 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004394 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004395 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004396}
4397
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004398// Look up classes by hash and descriptor and put all matching ones in the result array.
4399class LookupClassesVisitor : public ClassLoaderVisitor {
4400 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004401 LookupClassesVisitor(const char* descriptor,
4402 size_t hash,
4403 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004404 : descriptor_(descriptor),
4405 hash_(hash),
4406 result_(result) {}
4407
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004408 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004409 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004410 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004411 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004412 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4413 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004414 result_->push_back(klass);
4415 }
4416 }
4417
4418 private:
4419 const char* const descriptor_;
4420 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004421 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004422};
4423
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004424void ClassLinker::LookupClasses(const char* descriptor,
4425 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004426 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004427 Thread* const self = Thread::Current();
4428 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004429 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004430 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004431 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004432 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004433 result.push_back(klass);
4434 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004435 LookupClassesVisitor visitor(descriptor, hash, &result);
4436 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004437}
4438
Alex Lightf1f10492015-10-07 16:08:36 -07004439bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4440 Handle<mirror::Class> klass,
4441 Handle<mirror::Class> supertype) {
4442 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004443 DCHECK(klass != nullptr);
4444 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004445
Alex Lightf1f10492015-10-07 16:08:36 -07004446 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4447 VerifyClass(self, supertype);
4448 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004449
4450 if (supertype->IsVerified() || supertype->ShouldVerifyAtRuntime()) {
4451 // The supertype is either verified, or we soft failed at AOT time.
4452 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004453 return true;
4454 }
4455 // If we got this far then we have a hard failure.
4456 std::string error_msg =
4457 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004458 klass->PrettyDescriptor().c_str(),
4459 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004460 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004461 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004462 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004463 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004464 // Set during VerifyClass call (if at all).
4465 self->ClearException();
4466 }
4467 // Change into a verify error.
4468 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004469 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004470 self->GetException()->SetCause(cause.Get());
4471 }
4472 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4473 if (Runtime::Current()->IsAotCompiler()) {
4474 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4475 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004476 // Need to grab the lock to change status.
4477 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004478 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004479 return false;
4480}
4481
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004482verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004483 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004484 {
4485 // TODO: assert that the monitor on the Class is held
4486 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004487
Andreas Gampe884f3b82016-03-30 19:52:58 -07004488 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004489 ClassStatus old_status = klass->GetStatus();
4490 while (old_status == ClassStatus::kVerifying ||
4491 old_status == ClassStatus::kVerifyingAtRuntime) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004492 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004493 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4494 // case we may see the same status again. b/62912904. This is why the check is
4495 // greater or equal.
4496 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004497 << "Class '" << klass->PrettyClass()
4498 << "' performed an illegal verification state transition from " << old_status
4499 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004500 old_status = klass->GetStatus();
4501 }
jeffhao98eacac2011-09-14 16:11:53 -07004502
Andreas Gampe884f3b82016-03-30 19:52:58 -07004503 // The class might already be erroneous, for example at compile time if we attempted to verify
4504 // this class as a parent to another.
4505 if (klass->IsErroneous()) {
4506 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004507 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004508 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004509
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004510 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004511 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004512 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004513 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004514 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004515
4516 // For AOT, don't attempt to re-verify if we have already found we should
4517 // verify at runtime.
4518 if (Runtime::Current()->IsAotCompiler() && klass->ShouldVerifyAtRuntime()) {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004519 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004520 }
jeffhao98eacac2011-09-14 16:11:53 -07004521
Vladimir Marko2c64a832018-01-04 11:31:56 +00004522 if (klass->GetStatus() == ClassStatus::kResolved) {
4523 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004524 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004525 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime)
David Sehr709b0702016-10-13 09:12:37 -07004526 << klass->PrettyClass();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004527 CHECK(!Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004528 mirror::Class::SetStatus(klass, ClassStatus::kVerifyingAtRuntime, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004529 }
4530
4531 // Skip verification if disabled.
4532 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004533 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004534 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004535 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004536 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004537 }
4538
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004539 VLOG(class_linker) << "Beginning verification for class: "
4540 << klass->PrettyDescriptor()
4541 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4542
Ian Rogers9ffb0392012-09-10 11:56:50 -07004543 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004544 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004545 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4546 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004547 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004548 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004549 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004550 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004551
Alex Lightf1f10492015-10-07 16:08:36 -07004552 // Verify all default super-interfaces.
4553 //
4554 // (1) Don't bother if the superclass has already had a soft verification failure.
4555 //
4556 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4557 // recursive initialization by themselves. This is because when an interface is initialized
4558 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4559 // but choose not to for an optimization. If the interfaces is being verified due to a class
4560 // initialization (which would need all the default interfaces to be verified) the class code
4561 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004562 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004563 && !klass->IsInterface()) { // See (2)
4564 int32_t iftable_count = klass->GetIfTableCount();
4565 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4566 // Loop through all interfaces this class has defined. It doesn't matter the order.
4567 for (int32_t i = 0; i < iftable_count; i++) {
4568 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004569 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004570 // We only care if we have default interfaces and can skip if we are already verified...
4571 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4572 continue;
4573 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4574 // We had a hard failure while verifying this interface. Just return immediately.
4575 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004576 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004577 } else if (UNLIKELY(!iface->IsVerified())) {
4578 // We softly failed to verify the iface. Stop checking and clean up.
4579 // Put the iface into the supertype handle so we know what caused us to fail.
4580 supertype.Assign(iface.Get());
4581 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004582 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004583 }
4584 }
4585
Alex Lightf1f10492015-10-07 16:08:36 -07004586 // At this point if verification failed, then supertype is the "first" supertype that failed
4587 // verification (without a specific order). If verification succeeded, then supertype is either
4588 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004589 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004590 supertype.Get() == klass->GetSuperClass() ||
4591 !supertype->IsVerified());
4592
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004593 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004594 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004595 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004596 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004597
4598 VLOG(class_linker) << "Class preverified status for class "
4599 << klass->PrettyDescriptor()
4600 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4601 << ": "
4602 << preverified;
4603
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004604 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4605 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004606 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4607 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004608
Ian Rogers62d6c772013-02-27 08:32:07 -08004609 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004610 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004611 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004612 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004613 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004614
4615 // Verification is done, grab the lock again.
4616 ObjectLock<mirror::Class> lock(self, klass);
4617
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004618 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4619 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004620 VLOG(class_linker) << "Soft verification failure in class "
4621 << klass->PrettyDescriptor()
4622 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4623 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004624 }
Ian Rogers1f539342012-10-03 21:09:42 -07004625 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004626 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004627 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004628 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004629 // Even though there were no verifier failures we need to respect whether the super-class and
4630 // super-default-interfaces were verified or requiring runtime reverification.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004631 if (supertype == nullptr || supertype->IsVerified()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004632 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004633 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004634 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4635 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004636 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004637 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004638 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004639 } else {
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004640 CHECK_EQ(verifier_failure, verifier::FailureKind::kSoftFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004641 // Soft failures at compile time should be retried at runtime. Soft
4642 // failures at runtime will be handled by slow paths in the generated
4643 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004644 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004645 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004646 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004647 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004648 // As this is a fake verified status, make sure the methods are _not_ marked
4649 // kAccSkipAccessChecks later.
4650 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004651 }
4652 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004653 } else {
David Sehr709b0702016-10-13 09:12:37 -07004654 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004655 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4656 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004657 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004658 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004659 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004660 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004661 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004662 // Class is verified so we don't need to do any access check on its methods.
Igor Murashkindf707e42016-02-02 16:56:50 -08004663 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004664 // method.
4665 // Note: we're going here during compilation and at runtime. When we set the
Igor Murashkindf707e42016-02-02 16:56:50 -08004666 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02004667 // in the image and is set when loading the image.
Igor Murashkindf707e42016-02-02 16:56:50 -08004668
4669 if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
4670 // Never skip access checks if the verification soft fail is forced.
4671 // Mark the class as having a verification attempt to avoid re-running the verifier.
4672 klass->SetVerificationAttempted();
4673 } else {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004674 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004675 }
Andreas Gampe48498592014-09-10 19:48:05 -07004676 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004677 // Done verifying. Notify the compiler about the verification status, in case the class
4678 // was verified implicitly (eg super class of a compiled class).
4679 if (Runtime::Current()->IsAotCompiler()) {
4680 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4681 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4682 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004683 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004684}
4685
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004686verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4687 Handle<mirror::Class> klass,
4688 verifier::HardFailLogMode log_level,
4689 std::string* error_msg) {
4690 Runtime* const runtime = Runtime::Current();
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004691 return verifier::ClassVerifier::VerifyClass(self,
4692 klass.Get(),
4693 runtime->GetCompilerCallbacks(),
4694 runtime->IsAotCompiler(),
4695 log_level,
4696 Runtime::Current()->GetTargetSdkVersion(),
4697 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004698}
4699
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004700bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004701 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004702 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004703 // If we're compiling, we can only verify the class using the oat file if
4704 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004705 // the compilation unit (app - dependencies). We will let the compiler callback
4706 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004707 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004708 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004709 // Are we compiling the bootclasspath?
Andreas Gampee9934582018-01-19 21:23:04 -08004710 if (callbacks->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004711 return false;
4712 }
4713 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004714 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004715 return false;
4716 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004717 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004718
Andreas Gampeb40d3612018-06-26 15:49:42 -07004719 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004720 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004721 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Nicolas Geoffray144f82c2019-02-21 09:43:18 +00004722 if (!kIsDebugBuild && klass->GetClassLoader() == nullptr) {
4723 // For boot classpath classes in the case we're not using a default boot image:
4724 // we don't have the infrastructure yet to query verification data on individual
4725 // boot vdex files, so it's simpler for now to consider all boot classpath classes
4726 // verified. This should be taken into account when measuring boot time and app
4727 // startup compare to the (current) production system where both:
4728 // 1) updatable boot classpath classes, and
4729 // 2) classes in /system referencing updatable classes
4730 // will be verified at runtime.
4731 if (!Runtime::Current()->IsUsingDefaultBootImageLocation()) {
4732 oat_file_class_status = ClassStatus::kVerified;
4733 return true;
4734 }
4735 }
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004736 return false;
4737 }
4738
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004739 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004740 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004741 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004742 return true;
4743 }
4744 // If we only verified a subset of the classes at compile time, we can end up with classes that
4745 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004746 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004747 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004748 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004749 if (oat_file_class_status == ClassStatus::kRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07004750 // Compile time verification failed with a soft error. Compile time verification can fail
4751 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08004752 // class ... {
4753 // Foo x;
4754 // .... () {
4755 // if (...) {
4756 // v1 gets assigned a type of resolved class Foo
4757 // } else {
4758 // v1 gets assigned a type of unresolved class Bar
4759 // }
4760 // iput x = v1
4761 // } }
4762 // when we merge v1 following the if-the-else it results in Conflict
4763 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4764 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4765 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4766 // at compile time).
4767 return false;
4768 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00004769 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004770 // Compile time verification failed with a hard error. This is caused by invalid instructions
4771 // in the class. These errors are unrecoverable.
4772 return false;
4773 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004774 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004775 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4776 // not loading the class.
4777 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4778 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004779 return false;
4780 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004781 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004782 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004783 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004784 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004785 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004786}
4787
Alex Light5a559862016-01-29 12:24:48 -08004788void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004789 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004790 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004791 }
4792}
4793
Alex Light5a559862016-01-29 12:24:48 -08004794void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004795 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004796 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004797 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004798 return; // native or abstract method
4799 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004800 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004801 return; // nothing to process
4802 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004803 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004804 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004805 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4806 CatchHandlerIterator iterator(handlers_ptr);
4807 for (; iterator.HasNext(); iterator.Next()) {
4808 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4809 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004810 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004811 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004812 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004813 DCHECK(Thread::Current()->IsExceptionPending());
4814 Thread::Current()->ClearException();
4815 }
4816 }
4817 }
4818 handlers_ptr = iterator.EndDataPointer();
4819 }
4820}
4821
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004822ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4823 jstring name,
4824 jobjectArray interfaces,
4825 jobject loader,
4826 jobjectArray methods,
4827 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004828 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004829
4830 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4831 // code to be executed. We put it up here so we can avoid all the allocations associated with
4832 // creating the class. This can happen with (eg) jit-threads.
4833 if (!self->CanLoadClasses()) {
4834 // Make sure we don't try to load anything, potentially causing an infinite loop.
4835 ObjPtr<mirror::Throwable> pre_allocated =
4836 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4837 self->SetException(pre_allocated);
4838 return nullptr;
4839 }
4840
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004841 StackHandleScope<10> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004842 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004843 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004844 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004845 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004846 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004847 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004848 DCHECK(temp_klass->GetClass() != nullptr);
4849 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004850 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4851 // the methods.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004852 temp_klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4853 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4854 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4855 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004856 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004857 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004858 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004859 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004860 std::string storage;
4861 const char* descriptor = temp_klass->GetDescriptor(&storage);
4862 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004863
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004864 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004865 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004866
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004867 // Insert the class before loading the fields as the field roots
4868 // (ArtField::declaring_class_) are only visited from the class
4869 // table. There can't be any suspend points between inserting the
4870 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004871 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004872 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004873
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004874 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004875 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004876 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004877 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004878
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004879 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4880 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004881 ArtField& interfaces_sfield = sfields->At(0);
4882 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004883 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004884 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004885
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004886 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004887 ArtField& throws_sfield = sfields->At(1);
4888 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004889 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004890 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004891
Ian Rogers466bb252011-10-14 03:29:56 -07004892 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004893 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004894
Alex Lighte64300b2015-12-15 15:02:47 -08004895 // They have as many virtual methods as the array
Mathieu Chartier0795f232016-09-27 18:43:30 -07004896 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004897 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004898 << mirror::Class::PrettyClass(h_methods->GetClass());
Mathieu Chartierfc58af42015-04-16 18:00:39 -07004899 const size_t num_virtual_methods = h_methods->GetLength();
Alex Lighte64300b2015-12-15 15:02:47 -08004900
4901 // Create the methods array.
4902 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4903 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004904 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4905 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004906 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004907 self->AssertPendingOOMException();
4908 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004909 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004910 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004911
4912 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004913 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004914
4915 // Create virtual method using specified prototypes.
4916 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004917 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004918 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004919 auto* prototype = h_methods->Get(i)->GetArtMethod();
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004920 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004921 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4922 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004923 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004924
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004925 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004926 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004927 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004928 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004929 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004930
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004931 // At this point the class is loaded. Publish a ClassLoad event.
4932 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4933 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4934
4935 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004936 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004937 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004938 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004939 // Link the fields and virtual methods, creating vtable and iftables.
4940 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004941 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004942 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00004943 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004944 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004945 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004946 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004947 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004948 CHECK(temp_klass->IsRetired());
4949 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004950
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004951 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07004952 interfaces_sfield.SetObject<false>(
4953 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004954 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004955 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4956 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004957 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004958 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004959
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004960 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
4961
Vladimir Marko305c38b2018-02-14 11:50:07 +00004962 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
4963 // See also ClassLinker::EnsureInitialized().
4964 if (kBitstringSubtypeCheckEnabled) {
4965 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
4966 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
4967 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
4968 }
4969
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004970 {
4971 // Lock on klass is released. Lock new class object.
4972 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07004973 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004974 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07004975 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004976
4977 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07004978 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004979 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004980 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4981
Ian Rogersc2b44472011-12-14 21:17:17 -08004982 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004983 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4984 auto* prototype = h_methods->Get(i++)->GetArtMethod();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004985 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08004986 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004987
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004988 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07004989 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004990 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004991 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004992 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004993
4994 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07004995 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07004996 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08004997
Narayan Kamath6b2dc312017-03-14 13:26:12 +00004998 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07004999 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005000 CHECK_EQ(klass.Get()->GetProxyThrows(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005001 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08005002 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005003 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04005004}
5005
Mathieu Chartiere401d142015-04-22 13:56:20 -07005006void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
5007 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005008 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
5009 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01005010
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005011 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
5012 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07005013 ArtMethod* proxy_constructor =
5014 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005015 DCHECK(proxy_constructor != nullptr)
5016 << "Could not find <init> method in java.lang.reflect.Proxy";
5017
Jeff Haodb8a6642014-08-14 17:18:52 -07005018 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
5019 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07005020 DCHECK(out != nullptr);
5021 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01005022 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005023 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01005024 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005025 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
5026 kAccPublic |
5027 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005028 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005029
5030 // Set the original constructor method.
5031 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08005032}
5033
Mathieu Chartiere401d142015-04-22 13:56:20 -07005034void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005035 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005036 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
5037 CHECK_STREQ(np->GetName(), "<init>");
5038 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07005039 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04005040}
5041
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005042void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005043 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005044 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07005045 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07005046 DCHECK(out != nullptr);
5047 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07005048
Alex Lighte9dd04f2016-03-16 16:09:45 -07005049 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005050 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07005051 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
5052 // preference to the invocation handler.
5053 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
5054 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005055 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5056 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005057 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5058
5059 // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
5060 // method they copy might (if it's a default method).
5061 out->SetCodeItemOffset(0);
Jesse Wilson95caa792011-10-12 18:14:17 -04005062
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005063 // Set the original interface method.
5064 out->SetDataPtrSize(prototype, image_pointer_size_);
5065
Ian Rogers466bb252011-10-14 03:29:56 -07005066 // At runtime the method looks like a reference and argument saving method, clone the code
5067 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005068 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005069}
Jesse Wilson95caa792011-10-12 18:14:17 -04005070
Mathieu Chartiere401d142015-04-22 13:56:20 -07005071void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005072 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005073 CHECK(!prototype->IsFinal());
5074 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005075 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005076
5077 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5078 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005079 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005080 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005081}
5082
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005083bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005084 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005085 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005086 return true;
5087 }
5088 if (!can_init_statics) {
5089 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005090 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005091 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005092 return false;
5093 }
5094 // Check if there are encoded static values needing initialization.
5095 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005096 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005097 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005098 if (dex_class_def->static_values_off_ != 0) {
5099 return false;
5100 }
5101 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005102 // If we are a class we need to initialize all interfaces with default methods when we are
5103 // initialized. Check all of them.
5104 if (!klass->IsInterface()) {
5105 size_t num_interfaces = klass->GetIfTableCount();
5106 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005107 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07005108 if (iface->HasDefaultMethods() &&
5109 !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
5110 return false;
5111 }
5112 }
5113 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005114 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005115 if (klass->IsInterface() || !klass->HasSuperClass()) {
5116 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005117 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005118 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005119 if (!can_init_parents && !super_class->IsInitialized()) {
5120 return false;
5121 }
5122 return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005123}
5124
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005125bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
5126 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005127 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5128
5129 // Are we already initialized and therefore done?
5130 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5131 // an initialized class will never change its state.
5132 if (klass->IsInitialized()) {
5133 return true;
5134 }
5135
5136 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005137 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005138 return false;
5139 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005140
Ian Rogers7b078e82014-09-10 14:44:24 -07005141 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005142 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005143 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005144 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005145
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005146 // Re-check under the lock in case another thread initialized ahead of us.
5147 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005148 return true;
5149 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005150
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005151 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005152 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005153 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005154 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005155 return false;
5156 }
5157
Vladimir Marko72ab6842017-01-20 19:32:50 +00005158 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5159 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005160
5161 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005162 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005163 if (!klass->IsVerified()) {
5164 // We failed to verify, expect either the klass to be erroneous or verification failed at
5165 // compile time.
5166 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005167 // The class is erroneous. This may be a verifier error, or another thread attempted
5168 // verification and/or initialization and failed. We can distinguish those cases by
5169 // whether an exception is already pending.
5170 if (self->IsExceptionPending()) {
5171 // Check that it's a VerifyError.
5172 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005173 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005174 } else {
5175 // Check that another thread attempted initialization.
5176 DCHECK_NE(0, klass->GetClinitThreadId());
5177 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5178 // Need to rethrow the previous failure now.
5179 ThrowEarlierClassFailure(klass.Get(), true);
5180 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005181 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005182 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005183 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005184 CHECK_EQ(klass->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
Vladimir Markod79b37b2018-11-02 13:06:22 +00005185 self->AssertNoPendingException();
5186 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005187 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005188 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005189 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005190 } else {
5191 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005192 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005193
5194 // A separate thread could have moved us all the way to initialized. A "simple" example
5195 // involves a subclass of the current class being initialized at the same time (which
5196 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005197 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005198 if (klass->IsInitialized()) {
5199 return true;
5200 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005201 }
5202
Vladimir Marko2c64a832018-01-04 11:31:56 +00005203 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005204 // initializing higher up the stack or another thread has beat us
5205 // to initializing and we need to wait. Either way, this
5206 // invocation of InitializeClass will not be responsible for
5207 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005208 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005209 // Could have got an exception during verification.
5210 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005211 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005212 return false;
5213 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005214 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005215 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005216 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005217 return true;
5218 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005219 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005220 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005221 }
5222
Jeff Haoe2e40342017-07-19 10:45:18 -07005223 // Try to get the oat class's status for this class if the oat file is present. The compiler
5224 // tries to validate superclass descriptors, and writes the result into the oat file.
5225 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5226 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5227 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005228 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005229 const Runtime* runtime = Runtime::Current();
5230 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5231 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5232 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005233 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005234 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005235 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005236 return false;
5237 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005238 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005239
Vladimir Marko2c64a832018-01-04 11:31:56 +00005240 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005241 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005242
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005243 // From here out other threads may observe that we're initializing and so changes of state
5244 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005245 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005246 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005247
5248 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005249 }
5250
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005251 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005252 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005253 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005254 if (!super_class->IsInitialized()) {
5255 CHECK(!super_class->IsInterface());
5256 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005257 StackHandleScope<1> hs(self);
5258 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07005259 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005260 if (!super_initialized) {
5261 // The super class was verified ahead of entering initializing, we should only be here if
5262 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005263 // For the case of aot compiler, the super class might also be initializing but we don't
5264 // want to process circular dependencies in pre-compile.
5265 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005266 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005267 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005268 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005269 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005270 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005271 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005272 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005273 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005274 return false;
5275 }
Ian Rogers1bddec32012-02-04 12:27:34 -08005276 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005277 }
5278
Alex Lighteb7c1442015-08-31 13:17:42 -07005279 if (!klass->IsInterface()) {
5280 // Initialize interfaces with default methods for the JLS.
5281 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005282 // Only setup the (expensive) handle scope if we actually need to.
5283 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005284 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005285 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5286 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005287 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005288 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005289 CHECK(handle_scope_iface->IsInterface());
5290 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5291 // We have already done this for this interface. Skip it.
5292 continue;
5293 }
5294 // We cannot just call initialize class directly because we need to ensure that ALL
5295 // interfaces with default methods are initialized. Non-default interface initialization
5296 // will not affect other non-default super-interfaces.
5297 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5298 handle_scope_iface,
5299 can_init_statics,
5300 can_init_parents);
5301 if (!iface_initialized) {
5302 ObjectLock<mirror::Class> lock(self, klass);
5303 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005304 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005305 return false;
5306 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005307 }
5308 }
5309 }
5310
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005311 const size_t num_static_fields = klass->NumStaticFields();
5312 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005313 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005314 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005315 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005316 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005317 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005318
5319 // Eagerly fill in static fields so that the we don't have to do as many expensive
5320 // Class::FindStaticField in ResolveField.
5321 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005322 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005323 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005324 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005325 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005326 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005327 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5328 field,
5329 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5330 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005331 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005332 } else {
5333 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005334 }
5335 }
5336
Vladimir Markoe11dd502017-12-08 14:09:45 +00005337 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5338 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005339 this,
5340 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005341 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005342
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005343 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005344 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005345 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005346 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5347 if (!value_it.HasNext()) {
5348 break;
5349 }
5350 ArtField* art_field = ResolveField(field.GetIndex(),
5351 dex_cache,
5352 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005353 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005354 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005355 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005356 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005357 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005358 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005359 if (self->IsExceptionPending()) {
5360 break;
5361 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005362 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005363 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005364 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005365 }
5366 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005367
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005368
Mathieu Chartierda595be2016-08-10 13:57:39 -07005369 if (!self->IsExceptionPending()) {
5370 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5371 if (clinit != nullptr) {
5372 CHECK(can_init_statics);
5373 JValue result;
5374 clinit->Invoke(self, nullptr, 0, &result, "V");
5375 }
5376 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005377 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005378 uint64_t t1 = NanoTime();
5379
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005380 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005381 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005382 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005383
5384 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005385 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005386 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005387 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005388 } else if (Runtime::Current()->IsTransactionAborted()) {
5389 // The exception thrown when the transaction aborted has been caught and cleared
5390 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005391 VLOG(compiler) << "Return from class initializer of "
5392 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005393 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02005394 Runtime::Current()->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005395 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005396 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005397 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005398 RuntimeStats* global_stats = Runtime::Current()->GetStats();
5399 RuntimeStats* thread_stats = self->GetStats();
5400 ++global_stats->class_init_count;
5401 ++thread_stats->class_init_count;
5402 global_stats->class_init_time_ns += (t1 - t0);
5403 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005404 // Set the class as initialized except if failed to initialize static fields.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005405 mirror::Class::SetStatus(klass, ClassStatus::kInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005406 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005407 std::string temp;
5408 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005409 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005410 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08005411 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005412 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005413 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005414 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005415 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005416}
5417
Alex Lighteb7c1442015-08-31 13:17:42 -07005418// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5419// and perform the initialization only on those interfaces that contain default methods.
5420bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5421 Handle<mirror::Class> iface,
5422 bool can_init_statics,
5423 bool can_init_parents) {
5424 CHECK(iface->IsInterface());
5425 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005426 // Only create the (expensive) handle scope if we need it.
5427 if (UNLIKELY(num_direct_ifaces > 0)) {
5428 StackHandleScope<1> hs(self);
5429 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5430 // First we initialize all of iface's super-interfaces recursively.
5431 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005432 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005433 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005434 if (!super_iface->HasBeenRecursivelyInitialized()) {
5435 // Recursive step
5436 handle_super_iface.Assign(super_iface);
5437 if (!InitializeDefaultInterfaceRecursive(self,
5438 handle_super_iface,
5439 can_init_statics,
5440 can_init_parents)) {
5441 return false;
5442 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005443 }
5444 }
5445 }
5446
5447 bool result = true;
5448 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5449 // initialize if we don't have default methods.
5450 if (iface->HasDefaultMethods()) {
5451 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5452 }
5453
5454 // Mark that this interface has undergone recursive default interface initialization so we know we
5455 // can skip it on any later class initializations. We do this even if we are not a default
5456 // interface since we can still avoid the traversal. This is purely a performance optimization.
5457 if (result) {
5458 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005459 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5460 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5461 // initialization is a performance optimization (to avoid another idempotent visit
5462 // for other implementing classes/interfaces), and can be revisited later.
5463 ObjectTryLock<mirror::Class> lock(self, iface);
5464 if (lock.Acquired()) {
5465 iface->SetRecursivelyInitialized();
5466 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005467 }
5468 return result;
5469}
5470
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005471bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5472 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005473 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005474 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005475 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005476 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005477 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005478 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005479
5480 // When we wake up, repeat the test for init-in-progress. If
5481 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005482 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005483 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005484 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005485 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005486 return false;
5487 }
5488 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005489 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005490 continue;
5491 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005492 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005493 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005494 // Compile time initialization failed.
5495 return false;
5496 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005497 if (klass->IsErroneous()) {
5498 // The caller wants an exception, but it was thrown in a
5499 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005500 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005501 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005502 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005503 return false;
5504 }
5505 if (klass->IsInitialized()) {
5506 return true;
5507 }
David Sehr709b0702016-10-13 09:12:37 -07005508 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005509 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005510 }
Ian Rogers07140832014-09-30 15:43:59 -07005511 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005512}
5513
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005514static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5515 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005516 ArtMethod* method,
5517 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005518 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005519 DCHECK(Thread::Current()->IsExceptionPending());
5520 DCHECK(!m->IsProxyMethod());
5521 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005522 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5523 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005524 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005525 std::string return_type = dex_file->PrettyType(return_type_idx);
5526 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005527 ThrowWrappedLinkageError(klass.Get(),
5528 "While checking class %s method %s signature against %s %s: "
5529 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005530 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5531 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005532 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005533 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005534 return_type.c_str(), class_loader.c_str());
5535}
5536
5537static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5538 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005539 ArtMethod* method,
5540 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005541 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005542 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005543 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005544 DCHECK(Thread::Current()->IsExceptionPending());
5545 DCHECK(!m->IsProxyMethod());
5546 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005547 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5548 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005549 ThrowWrappedLinkageError(klass.Get(),
5550 "While checking class %s method %s signature against %s %s: "
5551 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005552 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5553 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005554 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005555 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005556 index, arg_type.c_str(), class_loader.c_str());
5557}
5558
5559static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5560 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005561 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005562 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005563 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005564 ThrowLinkageError(klass.Get(),
5565 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005566 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5567 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005568 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005569 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005570 error_msg.c_str());
5571}
5572
Ian Rogersb5fb2072014-12-02 17:22:02 -08005573static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005574 Handle<mirror::Class> klass,
5575 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005576 ArtMethod* method1,
5577 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005578 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005579 {
5580 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005581 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005582 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005583 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005584 return false;
5585 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005586 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005587 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005588 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005589 return false;
5590 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005591 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005592 ThrowSignatureMismatch(klass, super_klass, method1,
5593 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005594 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005595 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005596 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005597 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005598 return false;
5599 }
5600 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005601 const dex::TypeList* types1 = method1->GetParameterTypeList();
5602 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005603 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005604 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005605 ThrowSignatureMismatch(klass, super_klass, method1,
5606 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005607 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005608 return false;
5609 }
5610 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005611 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005612 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005613 ThrowSignatureMismatch(klass, super_klass, method1,
5614 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005615 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005616 return false;
5617 }
5618 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005619 }
5620 uint32_t num_types = types1->Size();
5621 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005622 ThrowSignatureMismatch(klass, super_klass, method1,
5623 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005624 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005625 return false;
5626 }
5627 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005628 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005629 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005630 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005631 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005632 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005633 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005634 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005635 return false;
5636 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005637 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005638 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005639 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005640 if (UNLIKELY(other_param_type == nullptr)) {
5641 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005642 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005643 return false;
5644 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005645 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005646 ThrowSignatureMismatch(klass, super_klass, method1,
5647 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5648 i,
David Sehr709b0702016-10-13 09:12:37 -07005649 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005650 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005651 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005652 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005653 return false;
5654 }
5655 }
5656 return true;
5657}
5658
5659
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005660bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005661 if (klass->IsInterface()) {
5662 return true;
5663 }
Ian Rogers151f2212014-05-06 11:27:27 -07005664 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005665 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005666 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005667 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005668 if (klass->HasSuperClass() &&
5669 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005670 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005671 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005672 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5673 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5674 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005675 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5676 klass,
5677 super_klass,
5678 m,
5679 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005680 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005681 return false;
5682 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005683 }
5684 }
5685 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005686 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005687 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5688 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5689 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005690 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005691 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5692 j, image_pointer_size_);
5693 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5694 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005695 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5696 klass,
5697 super_klass,
5698 m,
5699 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005700 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005701 return false;
5702 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005703 }
5704 }
5705 }
5706 }
5707 return true;
5708}
5709
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005710bool ClassLinker::EnsureInitialized(Thread* self,
5711 Handle<mirror::Class> c,
5712 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005713 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005714 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005715
Mathieu Chartier524507a2014-08-27 15:28:28 -07005716 if (c->IsInitialized()) {
Andreas Gampe5b20b352018-10-11 19:03:20 -07005717 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005718 return true;
5719 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005720 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5721 //
5722 // Ensure the bitstring is initialized before any of the class initialization
5723 // logic occurs. Once a class initializer starts running, objects can
5724 // escape into the heap and use the subtype checking code.
5725 //
5726 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5727 // can be used as a source for the IsSubClass check, and that all ancestors
5728 // of the class are Assigned (can be used as a target for IsSubClass check)
5729 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005730 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005731 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005732 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005733 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5734 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005735 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005736 if (!success) {
5737 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005738 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005739 }
5740 } else {
5741 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005742 }
5743 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005744}
5745
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005746void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5747 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005748 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005749 for (ArtField& field : new_class->GetIFields()) {
5750 if (field.GetDeclaringClass() == temp_class) {
5751 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005752 }
5753 }
5754
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005755 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005756 for (ArtField& field : new_class->GetSFields()) {
5757 if (field.GetDeclaringClass() == temp_class) {
5758 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005759 }
5760 }
5761
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005762 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005763 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005764 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005765 if (method.GetDeclaringClass() == temp_class) {
5766 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005767 }
5768 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005769
5770 // Make sure the remembered set and mod-union tables know that we updated some of the native
5771 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005772 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005773}
5774
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005775void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005776 CHECK(class_loader->GetAllocator() == nullptr);
5777 CHECK(class_loader->GetClassTable() == nullptr);
5778 Thread* const self = Thread::Current();
5779 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005780 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005781 // Create and set the class table.
5782 data.class_table = new ClassTable;
5783 class_loader->SetClassTable(data.class_table);
5784 // Create and set the linear allocator.
5785 data.allocator = Runtime::Current()->CreateLinearAlloc();
5786 class_loader->SetAllocator(data.allocator);
5787 // Add to the list so that we know to free the data later.
5788 class_loaders_.push_back(data);
5789}
5790
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005791ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005792 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005793 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005794 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005795 ClassTable* class_table = class_loader->GetClassTable();
5796 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005797 RegisterClassLoader(class_loader);
5798 class_table = class_loader->GetClassTable();
5799 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005800 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005801 return class_table;
5802}
5803
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005804ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005805 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005806}
5807
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005808static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005809 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005810 while (klass->HasSuperClass()) {
5811 klass = klass->GetSuperClass();
5812 if (klass->ShouldHaveImt()) {
5813 return klass->GetImt(pointer_size);
5814 }
5815 }
5816 return nullptr;
5817}
5818
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005819bool ClassLinker::LinkClass(Thread* self,
5820 const char* descriptor,
5821 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005822 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005823 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005824 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005825
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005826 if (!LinkSuperClass(klass)) {
5827 return false;
5828 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005829 ArtMethod* imt_data[ImTable::kSize];
5830 // If there are any new conflicts compared to super class.
5831 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005832 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005833 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005834 return false;
5835 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005836 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005837 return false;
5838 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005839 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005840 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005841 return false;
5842 }
5843 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005844 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005845
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005846 ImTable* imt = nullptr;
5847 if (klass->ShouldHaveImt()) {
5848 // If there are any new conflicts compared to the super class we can not make a copy. There
5849 // can be cases where both will have a conflict method at the same slot without having the same
5850 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5851 // will possibly create a table that is incorrect for either of the classes.
5852 // Same IMT with new_conflict does not happen very often.
5853 if (!new_conflict) {
5854 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5855 if (super_imt != nullptr) {
5856 bool imt_equals = true;
5857 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5858 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5859 }
5860 if (imt_equals) {
5861 imt = super_imt;
5862 }
5863 }
5864 }
5865 if (imt == nullptr) {
5866 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5867 imt = reinterpret_cast<ImTable*>(
5868 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5869 if (imt == nullptr) {
5870 return false;
5871 }
5872 imt->Populate(imt_data, image_pointer_size_);
5873 }
5874 }
5875
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005876 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5877 // We don't need to retire this class as it has no embedded tables or it was created the
5878 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005879 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005880
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005881 if (klass->ShouldHaveEmbeddedVTable()) {
5882 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005883 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005884 if (klass->ShouldHaveImt()) {
5885 klass->SetImt(imt, image_pointer_size_);
5886 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005887
5888 // Update CHA info based on whether we override methods.
5889 // Have to do this before setting the class as resolved which allows
5890 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005891 if (cha_ != nullptr) {
5892 cha_->UpdateAfterLoadingOf(klass);
5893 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005894
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005895 // This will notify waiters on klass that saw the not yet resolved
5896 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005897 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005898 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005899 } else {
5900 CHECK(!klass->IsResolved());
5901 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005902 StackHandleScope<1> hs(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005903 auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005904 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5905 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5906 // may not see any references to the target space and clean the card for a class if another
5907 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005908 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005909 klass->SetSFieldsPtrUnchecked(nullptr);
5910 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005911 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005912 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005913 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005914 return false;
5915 }
5916
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005917 CHECK_EQ(h_new_class->GetClassSize(), class_size);
5918 ObjectLock<mirror::Class> lock(self, h_new_class);
5919 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005920
5921 {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005922 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00005923 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005924 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00005925 const ObjPtr<mirror::Class> existing =
5926 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005927 if (class_loader != nullptr) {
5928 // We updated the class in the class table, perform the write barrier so that the GC knows
5929 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005930 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07005931 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005932 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00005933 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005934 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5935 }
5936 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005937
Mingyao Yang063fc772016-08-02 11:02:54 -07005938 // Update CHA info based on whether we override methods.
5939 // Have to do this before setting the class as resolved which allows
5940 // instantiation of klass.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005941 if (cha_ != nullptr) {
5942 cha_->UpdateAfterLoadingOf(h_new_class);
5943 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005944
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005945 // This will notify waiters on temp class that saw the not yet resolved class in the
5946 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005947 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005948
Vladimir Marko2c64a832018-01-04 11:31:56 +00005949 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005950 // This will notify waiters on new_class that saw the not yet resolved
5951 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005952 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005953 // Return the new class.
5954 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005955 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005956 return true;
5957}
5958
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005959bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005960 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005961 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08005962 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
5963 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01005964 // Check that a class does not inherit from itself directly.
5965 //
5966 // TODO: This is a cheap check to detect the straightforward case
5967 // of a class extending itself (b/28685551), but we should do a
5968 // proper cycle detection on loaded classes, to detect all cases
5969 // of class circularity errors (b/28830038).
5970 if (super_class_idx == class_def.class_idx_) {
5971 ThrowClassCircularityError(klass.Get(),
5972 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07005973 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01005974 return false;
5975 }
5976
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005977 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005978 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07005979 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005980 return false;
5981 }
Ian Rogersbe125a92012-01-11 15:19:49 -08005982 // Verify
5983 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005984 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07005985 super_class->PrettyDescriptor().c_str(),
5986 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08005987 return false;
5988 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005989 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005990 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005991 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005992 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005993 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005994 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08005995 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00005996 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005997 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005998 DCHECK(Thread::Current()->IsExceptionPending());
5999 return false;
6000 }
6001 // Verify
6002 if (!klass->CanAccess(interface)) {
6003 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006004 ThrowIllegalAccessError(klass.Get(),
6005 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006006 interface->PrettyDescriptor().c_str(),
6007 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006008 return false;
6009 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006010 }
6011 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07006012 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006013 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006014 return true;
6015}
6016
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006017bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006018 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006019 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006020 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
6021 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006022 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006023 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006024 return false;
6025 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006026 return true;
6027 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006028 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006029 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07006030 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006031 return false;
6032 }
6033 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006034 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00006035 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
6036 return false;
6037 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01006038 if (super->IsFinal()) {
6039 ThrowVerifyError(klass.Get(),
6040 "Superclass %s of %s is declared final",
6041 super->PrettyDescriptor().c_str(),
6042 klass->PrettyDescriptor().c_str());
6043 return false;
6044 }
6045 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006046 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006047 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07006048 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006049 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006050 return false;
6051 }
6052 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006053 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006054 super->PrettyDescriptor().c_str(),
6055 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006056 return false;
6057 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006058
Brian Carlstromf3632832014-05-20 15:36:53 -07006059 // Inherit kAccClassIsFinalizable from the superclass in case this
6060 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006061 if (super->IsFinalizable()) {
6062 klass->SetFinalizable();
6063 }
6064
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006065 // Inherit class loader flag form super class.
6066 if (super->IsClassLoaderClass()) {
6067 klass->SetClassLoaderClass();
6068 }
6069
Elliott Hughes2da50362011-10-10 16:57:08 -07006070 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006071 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006072 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006073 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006074 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006075 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006076 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006077 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006078 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006079 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006080 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006081 return false;
6082 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006083
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006084 if (kIsDebugBuild) {
6085 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006086 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006087 CHECK(super->IsResolved());
6088 super = super->GetSuperClass();
6089 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006090 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006091 return true;
6092}
6093
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006094// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006095bool ClassLinker::LinkMethods(Thread* self,
6096 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006097 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006098 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006099 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006100 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006101 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6102 // need to have default methods be in the virtuals array of each class but we don't set that up
6103 // until LinkInterfaceMethods.
Alex Light9139e002015-10-09 15:59:48 -07006104 std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
Alex Lighteb7c1442015-08-31 13:17:42 -07006105 // Link virtual methods then interface methods.
6106 // We set up the interface lookup table first because we need it to determine if we need to update
6107 // any vtable entries with new default method implementations.
6108 return SetupInterfaceLookupTable(self, klass, interfaces)
6109 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006110 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006111}
6112
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006113// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6114// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6115// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006116class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006117 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006118 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006119 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006120 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6121 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006122 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006123 }
6124
6125 const char* GetName() {
6126 if (name_ == nullptr) {
6127 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6128 }
6129 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006130 }
6131
Mathieu Chartiere401d142015-04-22 13:56:20 -07006132 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006133 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006134 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006135 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006136 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006137 if (dex_file_ == other_dex_file) {
6138 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6139 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006140 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006141 uint32_t other_name_len;
6142 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6143 &other_name_len);
6144 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6145 return false;
6146 }
6147 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6148 }
6149
6150 private:
6151 // Dex file for the method to compare against.
6152 const DexFile* const dex_file_;
6153 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006154 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006155 // Lazily computed name from the dex file's strings.
6156 const char* name_;
6157 // Lazily computed name length.
6158 uint32_t name_len_;
6159};
6160
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006161class LinkVirtualHashTable {
6162 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006163 LinkVirtualHashTable(Handle<mirror::Class> klass,
6164 size_t hash_size,
6165 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006166 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006167 : klass_(klass),
6168 hash_size_(hash_size),
6169 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006170 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006171 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6172 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006173
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006174 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006175 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6176 virtual_method_index, image_pointer_size_);
6177 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006178 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006179 uint32_t index = hash % hash_size_;
6180 // Linear probe until we have an empty slot.
6181 while (hash_table_[index] != invalid_index_) {
6182 if (++index == hash_size_) {
6183 index = 0;
6184 }
6185 }
6186 hash_table_[index] = virtual_method_index;
6187 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006188
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006189 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006190 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006191 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006192 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006193 size_t index = hash % hash_size_;
6194 while (true) {
6195 const uint32_t value = hash_table_[index];
6196 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6197 // the block and can safely assume not found.
6198 if (value == invalid_index_) {
6199 break;
6200 }
6201 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006202 ArtMethod* virtual_method =
6203 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6204 if (comparator->HasSameNameAndSignature(
6205 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006206 hash_table_[index] = removed_index_;
6207 return value;
6208 }
6209 }
6210 if (++index == hash_size_) {
6211 index = 0;
6212 }
6213 }
6214 return GetNotFoundIndex();
6215 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006216
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006217 static uint32_t GetNotFoundIndex() {
6218 return invalid_index_;
6219 }
6220
6221 private:
6222 static const uint32_t invalid_index_;
6223 static const uint32_t removed_index_;
6224
6225 Handle<mirror::Class> klass_;
6226 const size_t hash_size_;
6227 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006228 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006229};
6230
6231const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6232const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6233
Stephen Hines1ddd9132017-02-08 01:51:18 -08006234bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006235 Thread* self,
6236 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07006237 /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006238 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006239 if (klass->IsInterface()) {
6240 // No vtable.
6241 if (!IsUint<16>(num_virtual_methods)) {
6242 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6243 return false;
6244 }
6245 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006246 // Assign each method an IMT index and set the default flag.
6247 for (size_t i = 0; i < num_virtual_methods; ++i) {
6248 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6249 m->SetMethodIndex(i);
6250 if (!m->IsAbstract()) {
6251 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6252 has_defaults = true;
6253 }
6254 }
6255 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6256 // during initialization. This is a performance optimization. We could simply traverse the
6257 // virtual_methods_ array again during initialization.
6258 if (has_defaults) {
6259 klass->SetHasDefaultMethods();
6260 }
6261 return true;
6262 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006263 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6264 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006265 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006266 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006267 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006268 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006269 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006270 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006271 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006272 return false;
6273 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006274 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006275 vtable->SetElementPtrSize(
6276 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006277 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006278 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6279 // might give us new default methods). If no new interfaces then we can skip the rest since
6280 // the class cannot override any of the super-class's methods. This is required for
6281 // correctness since without it we might not update overridden default method vtable entries
6282 // correctly.
6283 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006284 klass->SetVTable(vtable.Get());
6285 return true;
6286 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006287 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006288 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Vladimir Markoc524e9e2019-03-26 10:54:50 +00006289 ObjPtr<mirror::PointerArray> super_vtable = super_class->GetVTable();
David Sehr709b0702016-10-13 09:12:37 -07006290 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006291 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6292 // might give us new default methods). See comment above.
6293 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006294 klass->SetVTable(super_vtable);
6295 return true;
6296 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006297 vtable = hs.NewHandle(
6298 ObjPtr<mirror::PointerArray>::DownCast(super_vtable->CopyOf(self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006299 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006300 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006301 return false;
6302 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006303 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006304 // How the algorithm works:
6305 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6306 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6307 // method which has not been matched to a vtable method, and j if the virtual method at the
6308 // index overrode the super virtual method at index j.
6309 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6310 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6311 // the need for the initial vtable which we later shrink back down).
6312 // 3. Add non overridden methods to the end of the vtable.
6313 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006314 // + 1 so that even if we only have new default methods we will still be able to use this hash
6315 // table (i.e. it will never have 0 size).
6316 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006317 uint32_t* hash_table_ptr;
6318 std::unique_ptr<uint32_t[]> hash_heap_storage;
6319 if (hash_table_size <= kMaxStackHash) {
6320 hash_table_ptr = reinterpret_cast<uint32_t*>(
6321 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6322 } else {
6323 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6324 hash_table_ptr = hash_heap_storage.get();
6325 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006326 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006327 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006328 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006329 DCHECK(klass->GetVirtualMethodDuringLinking(
6330 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006331 hash_table.Add(i);
6332 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006333 // 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 -07006334 // the hash table.
6335 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006336 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006337 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006338 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6339 super_method->GetAccessFlags())) {
6340 // Continue on to the next method since this one is package private and canot be overridden.
6341 // Before Android 4.1, the package-private method super_method might have been incorrectly
6342 // overridden.
6343 continue;
6344 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006345 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006346 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006347 // We remove the method so that subsequent lookups will be faster by making the hash-map
6348 // smaller as we go on.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006349 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
6350 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006351 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6352 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006353 if (super_method->IsFinal()) {
6354 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6355 virtual_method->PrettyMethod().c_str(),
6356 super_method->GetDeclaringClassDescriptor());
6357 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006358 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006359 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6360 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006361 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006362 // We didn't directly override this method but we might through default methods...
6363 // Check for default method update.
6364 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006365 switch (FindDefaultMethodImplementation(self,
6366 super_method,
6367 klass,
6368 /*out*/&default_method)) {
6369 case DefaultMethodSearchResult::kDefaultConflict: {
6370 // A conflict was found looking for default methods. Note this (assuming it wasn't
6371 // pre-existing) in the translations map.
6372 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6373 // Don't generate another conflict method to reduce memory use as an optimization.
6374 default_translations->insert(
6375 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6376 }
6377 break;
6378 }
6379 case DefaultMethodSearchResult::kAbstractFound: {
6380 // No conflict but method is abstract.
6381 // We note that this vtable entry must be made abstract.
6382 if (UNLIKELY(!super_method->IsAbstract())) {
6383 default_translations->insert(
6384 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6385 }
6386 break;
6387 }
6388 case DefaultMethodSearchResult::kDefaultFound: {
6389 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6390 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6391 // Found a default method implementation that is new.
6392 // TODO Refactor this add default methods to virtuals here and not in
6393 // LinkInterfaceMethods maybe.
6394 // The problem is default methods might override previously present
6395 // default-method or miranda-method vtable entries from the superclass.
6396 // Unfortunately we need these to be entries in this class's virtuals. We do not
6397 // give these entries there until LinkInterfaceMethods so we pass this map around
6398 // to let it know which vtable entries need to be updated.
6399 // Make a note that vtable entry j must be updated, store what it needs to be updated
6400 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6401 // then.
6402 default_translations->insert(
6403 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006404 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6405 << " overridden by default "
6406 << default_method->PrettyMethod()
6407 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006408 }
6409 break;
6410 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006411 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006412 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006413 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006414 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006415 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006416 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006417 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006418 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6419 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006420 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006421 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006422 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006423 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006424 local_method->SetMethodIndex(actual_count);
6425 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006426 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006427 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006428 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006429 return false;
6430 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006431 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006432 CHECK_LE(actual_count, max_count);
6433 if (actual_count < max_count) {
Vladimir Markobcf17522018-06-01 13:14:32 +01006434 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(vtable->CopyOf(self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006435 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006436 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006437 return false;
6438 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006439 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006440 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006441 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006442 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006443 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006444 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6445 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006446 return false;
6447 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006448 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006449 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006450 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006451 return false;
6452 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006453 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006454 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6455 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006456 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006457 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006458 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006459 }
6460 return true;
6461}
6462
Alex Light9139e002015-10-09 15:59:48 -07006463// Determine if the given iface has any subinterface in the given list that declares the method
6464// specified by 'target'.
6465//
6466// Arguments
6467// - self: The thread we are running on
6468// - target: A comparator that will match any method that overrides the method we are checking for
6469// - iftable: The iftable we are searching for an overriding method on.
6470// - ifstart: The index of the interface we are checking to see if anything overrides
6471// - iface: The interface we are checking to see if anything overrides.
6472// - image_pointer_size:
6473// The image pointer size.
6474//
6475// Returns
6476// - True: There is some method that matches the target comparator defined in an interface that
6477// is a subtype of iface.
6478// - False: There is no method that matches the target comparator in any interface that is a subtype
6479// of iface.
6480static bool ContainsOverridingMethodOf(Thread* self,
6481 MethodNameAndSignatureComparator& target,
6482 Handle<mirror::IfTable> iftable,
6483 size_t ifstart,
6484 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006485 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006486 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006487 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006488 DCHECK(iface != nullptr);
6489 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006490 DCHECK_GE(ifstart, 0u);
6491 DCHECK_LT(ifstart, iftable->Count());
6492 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6493 DCHECK(iface->IsInterface());
6494
6495 size_t iftable_count = iftable->Count();
6496 StackHandleScope<1> hs(self);
6497 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6498 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6499 // Skip ifstart since our current interface obviously cannot override itself.
6500 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006501 // Iterate through every method on this interface. The order does not matter.
6502 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006503 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006504 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006505 // Check if the i'th interface is a subtype of this one.
6506 if (iface->IsAssignableFrom(current_iface.Get())) {
6507 return true;
6508 }
6509 break;
6510 }
6511 }
6512 }
6513 return false;
6514}
6515
Alex Lighteb7c1442015-08-31 13:17:42 -07006516// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006517// out_default_method and returns kDefaultFound on success. If no default method was found return
6518// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6519// default_method conflict) it will return kDefaultConflict.
6520ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6521 Thread* self,
6522 ArtMethod* target_method,
6523 Handle<mirror::Class> klass,
6524 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006525 DCHECK(self != nullptr);
6526 DCHECK(target_method != nullptr);
6527 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006528
6529 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006530
6531 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6532 // table. This lets us walk the table backwards when searching for default methods. The first one
6533 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6534 // track of it and then continue checking all other interfaces, since we need to throw an error if
6535 // we encounter conflicting default method implementations (one is not a subtype of the other).
6536 //
6537 // The order of unrelated interfaces does not matter and is not defined.
6538 size_t iftable_count = klass->GetIfTableCount();
6539 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006540 // No interfaces. We have already reset out to null so just return kAbstractFound.
6541 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006542 }
6543
Alex Light9139e002015-10-09 15:59:48 -07006544 StackHandleScope<3> hs(self);
6545 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006546 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006547 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006548 MethodNameAndSignatureComparator target_name_comparator(
6549 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6550 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006551 for (size_t k = iftable_count; k != 0; ) {
6552 --k;
6553
Alex Lighteb7c1442015-08-31 13:17:42 -07006554 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006555
6556 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006557 // Iterate through every declared method on this interface. The order does not matter.
6558 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6559 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006560 // Skip abstract methods and methods with different names.
6561 if (current_method->IsAbstract() ||
6562 !target_name_comparator.HasSameNameAndSignature(
6563 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6564 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006565 } else if (!current_method->IsPublic()) {
6566 // The verifier should have caught the non-public method for dex version 37. Just warn and
6567 // skip it since this is from before default-methods so we don't really need to care that it
6568 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006569 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6570 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006571 << "This will be a fatal error in subsequent versions of android. "
6572 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006573 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006574 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006575 // We have multiple default impls of the same method. This is a potential default conflict.
6576 // We need to check if this possibly conflicting method is either a superclass of the chosen
6577 // default implementation or is overridden by a non-default interface method. In either case
6578 // there is no conflict.
6579 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6580 !ContainsOverridingMethodOf(self,
6581 target_name_comparator,
6582 iftable,
6583 k,
6584 iface,
6585 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006586 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006587 << current_method->PrettyMethod() << " and "
6588 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6589 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006590 *out_default_method = nullptr;
6591 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006592 } else {
6593 break; // Continue checking at the next interface.
6594 }
6595 } else {
Alex Light9139e002015-10-09 15:59:48 -07006596 // chosen_iface == null
6597 if (!ContainsOverridingMethodOf(self,
6598 target_name_comparator,
6599 iftable,
6600 k,
6601 iface,
6602 image_pointer_size_)) {
6603 // Don't set this as the chosen interface if something else is overriding it (because that
6604 // other interface would be potentially chosen instead if it was default). If the other
6605 // interface was abstract then we wouldn't select this interface as chosen anyway since
6606 // the abstract method masks it.
6607 *out_default_method = current_method;
6608 chosen_iface.Assign(iface.Get());
6609 // We should now finish traversing the graph to find if we have default methods that
6610 // conflict.
6611 } else {
David Sehr709b0702016-10-13 09:12:37 -07006612 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6613 << "' was "
6614 << "skipped because it was overridden by an abstract method in a "
6615 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006616 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006617 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006618 break;
6619 }
6620 }
Alex Light9139e002015-10-09 15:59:48 -07006621 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006622 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6623 << "' selected "
6624 << "as the implementation for '" << target_method->PrettyMethod()
6625 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006626 return DefaultMethodSearchResult::kDefaultFound;
6627 } else {
6628 return DefaultMethodSearchResult::kAbstractFound;
6629 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006630}
6631
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006632ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006633 ArtMethod* conflict_method,
6634 ArtMethod* interface_method,
6635 ArtMethod* method,
6636 bool force_new_conflict_method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006637 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006638 Runtime* const runtime = Runtime::Current();
6639 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6640 bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6641
6642 // Create a new entry if the existing one is the shared conflict method.
6643 ArtMethod* new_conflict_method = new_entry
6644 ? runtime->CreateImtConflictMethod(linear_alloc)
6645 : conflict_method;
6646
6647 // Allocate a new table. Note that we will leak this table at the next conflict,
6648 // but that's a tradeoff compared to making the table fixed size.
6649 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006650 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6651 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006652 if (data == nullptr) {
6653 LOG(ERROR) << "Failed to allocate conflict table";
6654 return conflict_method;
6655 }
6656 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6657 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006658 method,
6659 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006660
6661 // Do a fence to ensure threads see the data in the table before it is assigned
6662 // to the conflict method.
6663 // Note that there is a race in the presence of multiple threads and we may leak
6664 // memory from the LinearAlloc, but that's a tradeoff compared to using
6665 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006666 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006667 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006668 return new_conflict_method;
6669}
6670
Vladimir Marko921094a2017-01-12 18:37:06 +00006671bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6672 Handle<mirror::Class> klass,
6673 Handle<mirror::IfTable> iftable) {
6674 DCHECK(!klass->IsInterface());
6675 const bool has_superclass = klass->HasSuperClass();
6676 const bool extend_super_iftable = has_superclass;
6677 const size_t ifcount = klass->GetIfTableCount();
6678 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6679 for (size_t i = 0; i < ifcount; ++i) {
6680 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6681 if (num_methods > 0) {
6682 const bool is_super = i < super_ifcount;
6683 // This is an interface implemented by a super-class. Therefore we can just copy the method
6684 // array from the superclass.
6685 const bool super_interface = is_super && extend_super_iftable;
6686 ObjPtr<mirror::PointerArray> method_array;
6687 if (super_interface) {
6688 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6689 DCHECK(if_table != nullptr);
6690 DCHECK(if_table->GetMethodArray(i) != nullptr);
6691 // If we are working on a super interface, try extending the existing method array.
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00006692 method_array = ObjPtr<mirror::PointerArray>::DownCast(
6693 if_table->GetMethodArray(i)->Clone(self));
Vladimir Marko921094a2017-01-12 18:37:06 +00006694 } else {
6695 method_array = AllocPointerArray(self, num_methods);
6696 }
6697 if (UNLIKELY(method_array == nullptr)) {
6698 self->AssertPendingOOMException();
6699 return false;
6700 }
6701 iftable->SetMethodArray(i, method_array);
6702 }
6703 }
6704 return true;
6705}
6706
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006707void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6708 ArtMethod* imt_conflict_method,
6709 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006710 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006711 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006712 // Place method in imt if entry is empty, place conflict otherwise.
6713 if (*imt_ref == unimplemented_method) {
6714 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006715 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006716 // If we are not a conflict and we have the same signature and name as the imt
6717 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006718 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6719 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006720 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006721 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006722 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006723 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006724 *imt_ref = current_method;
6725 } else {
Alex Light9139e002015-10-09 15:59:48 -07006726 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006727 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006728 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006729 } else {
6730 // Place the default conflict method. Note that there may be an existing conflict
6731 // method in the IMT, but it could be one tailored to the super class, with a
6732 // specific ImtConflictTable.
6733 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006734 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006735 }
6736}
6737
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006738void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006739 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6740 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006741 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006742 Runtime* const runtime = Runtime::Current();
6743 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6744 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006745 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006746 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006747 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006748 FillIMTFromIfTable(klass->GetIfTable(),
6749 unimplemented_method,
6750 conflict_method,
6751 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006752 /*create_conflict_tables=*/true,
6753 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006754 &new_conflict,
6755 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006756 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006757 if (!klass->ShouldHaveImt()) {
6758 return;
6759 }
6760 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6761 // we can just use the same pointer.
6762 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006763 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006764 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6765 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6766 bool same = true;
6767 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6768 ArtMethod* method = imt_data[i];
6769 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6770 if (method != super_method) {
6771 bool is_conflict_table = method->IsRuntimeMethod() &&
6772 method != unimplemented_method &&
6773 method != conflict_method;
6774 // Verify conflict contents.
6775 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6776 super_method != unimplemented_method &&
6777 super_method != conflict_method;
6778 if (!is_conflict_table || !super_conflict_table) {
6779 same = false;
6780 } else {
6781 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6782 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6783 same = same && table1->Equals(table2, image_pointer_size_);
6784 }
6785 }
6786 }
6787 if (same) {
6788 imt = super_imt;
6789 }
6790 }
6791 if (imt == nullptr) {
6792 imt = klass->GetImt(image_pointer_size_);
6793 DCHECK(imt != nullptr);
6794 imt->Populate(imt_data, image_pointer_size_);
6795 } else {
6796 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006797 }
6798}
6799
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006800ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6801 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006802 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006803 void* data = linear_alloc->Alloc(Thread::Current(),
6804 ImtConflictTable::ComputeSize(count,
6805 image_pointer_size));
6806 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6807}
6808
6809ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6810 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6811}
6812
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006813void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006814 ArtMethod* unimplemented_method,
6815 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006816 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006817 bool create_conflict_tables,
6818 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006819 /*out*/bool* new_conflict,
6820 /*out*/ArtMethod** imt) {
6821 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006822 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006823 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006824 const size_t num_virtuals = interface->NumVirtualMethods();
6825 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6826 // Virtual methods can be larger than the if table methods if there are default methods.
6827 DCHECK_GE(num_virtuals, method_array_count);
6828 if (kIsDebugBuild) {
6829 if (klass->IsInterface()) {
6830 DCHECK_EQ(method_array_count, 0u);
6831 } else {
6832 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6833 }
6834 }
6835 if (method_array_count == 0) {
6836 continue;
6837 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006838 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006839 for (size_t j = 0; j < method_array_count; ++j) {
6840 ArtMethod* implementation_method =
6841 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6842 if (ignore_copied_methods && implementation_method->IsCopied()) {
6843 continue;
6844 }
6845 DCHECK(implementation_method != nullptr);
6846 // Miranda methods cannot be used to implement an interface method, but they are safe to put
6847 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6848 // or interface methods in the IMT here they will not create extra conflicts since we compare
6849 // names and signatures in SetIMTRef.
6850 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006851 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006852
6853 // There is only any conflicts if all of the interface methods for an IMT slot don't have
6854 // the same implementation method, keep track of this to avoid creating a conflict table in
6855 // this case.
6856
6857 // Conflict table size for each IMT slot.
6858 ++conflict_counts[imt_index];
6859
6860 SetIMTRef(unimplemented_method,
6861 imt_conflict_method,
6862 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006863 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006864 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006865 }
6866 }
6867
6868 if (create_conflict_tables) {
6869 // Create the conflict tables.
6870 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006871 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006872 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006873 if (imt[i] == imt_conflict_method) {
6874 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6875 if (new_table != nullptr) {
6876 ArtMethod* new_conflict_method =
6877 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6878 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6879 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006880 } else {
6881 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006882 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006883 }
6884 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006885 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006886 }
6887 }
6888
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006889 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006890 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006891 const size_t method_array_count = if_table->GetMethodArrayCount(i);
6892 // Virtual methods can be larger than the if table methods if there are default methods.
6893 if (method_array_count == 0) {
6894 continue;
6895 }
Vladimir Marko557fece2019-03-26 14:29:41 +00006896 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006897 for (size_t j = 0; j < method_array_count; ++j) {
6898 ArtMethod* implementation_method =
6899 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6900 if (ignore_copied_methods && implementation_method->IsCopied()) {
6901 continue;
6902 }
6903 DCHECK(implementation_method != nullptr);
6904 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00006905 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006906 if (!imt[imt_index]->IsRuntimeMethod() ||
6907 imt[imt_index] == unimplemented_method ||
6908 imt[imt_index] == imt_conflict_method) {
6909 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006910 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006911 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6912 const size_t num_entries = table->NumEntries(image_pointer_size_);
6913 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6914 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006915 }
6916 }
6917 }
6918}
6919
Alex Lighteb7c1442015-08-31 13:17:42 -07006920// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6921// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006922static bool NotSubinterfaceOfAny(
6923 const std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr>& classes,
6924 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07006925 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006926 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006927 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006928 for (ObjPtr<mirror::Class> c : classes) {
6929 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006930 return false;
6931 }
6932 }
6933 return true;
6934}
6935
6936// Fills in and flattens the interface inheritance hierarchy.
6937//
6938// By the end of this function all interfaces in the transitive closure of to_process are added to
6939// the iftable and every interface precedes all of its sub-interfaces in this list.
6940//
6941// all I, J: Interface | I <: J implies J precedes I
6942//
6943// (note A <: B means that A is a subtype of B)
6944//
6945// This returns the total number of items in the iftable. The iftable might be resized down after
6946// this call.
6947//
6948// We order this backwards so that we do not need to reorder superclass interfaces when new
6949// interfaces are added in subclass's interface tables.
6950//
6951// Upon entry into this function iftable is a copy of the superclass's iftable with the first
6952// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6953// The other entries are uninitialized. We will fill in the remaining entries in this function. The
6954// iftable must be large enough to hold all interfaces without changing its size.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006955static size_t FillIfTable(ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07006956 size_t super_ifcount,
Stephen Hines48ba1972018-09-24 13:35:54 -07006957 const std::vector<ObjPtr<mirror::Class>>& to_process)
Alex Lighteb7c1442015-08-31 13:17:42 -07006958 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006959 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006960 // This is the set of all class's already in the iftable. Used to make checking if a class has
6961 // already been added quicker.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006962 std::unordered_set<ObjPtr<mirror::Class>, HashObjPtr> classes_in_iftable;
Alex Lighteb7c1442015-08-31 13:17:42 -07006963 // The first super_ifcount elements are from the superclass. We note that they are already added.
6964 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006965 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07006966 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6967 classes_in_iftable.insert(iface);
6968 }
6969 size_t filled_ifcount = super_ifcount;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006970 for (ObjPtr<mirror::Class> interface : to_process) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006971 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6972 // At this point in the loop current-iface-list has the invariant that:
6973 // for every pair of interfaces I,J within it:
6974 // if index_of(I) < index_of(J) then I is not a subtype of J
6975
6976 // If we have already seen this element then all of its super-interfaces must already be in the
6977 // current-iface-list so we can skip adding it.
6978 if (!ContainsElement(classes_in_iftable, interface)) {
6979 // We haven't seen this interface so add all of its super-interfaces onto the
6980 // current-iface-list, skipping those already on it.
6981 int32_t ifcount = interface->GetIfTableCount();
6982 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006983 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07006984 if (!ContainsElement(classes_in_iftable, super_interface)) {
6985 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6986 classes_in_iftable.insert(super_interface);
6987 iftable->SetInterface(filled_ifcount, super_interface);
6988 filled_ifcount++;
6989 }
6990 }
6991 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6992 // Place this interface onto the current-iface-list after all of its super-interfaces.
6993 classes_in_iftable.insert(interface);
6994 iftable->SetInterface(filled_ifcount, interface);
6995 filled_ifcount++;
6996 } else if (kIsDebugBuild) {
6997 // Check all super-interfaces are already in the list.
6998 int32_t ifcount = interface->GetIfTableCount();
6999 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007000 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007001 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07007002 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
7003 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07007004 }
7005 }
7006 }
7007 if (kIsDebugBuild) {
7008 // Check that the iftable is ordered correctly.
7009 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007010 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007011 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007012 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007013 // !(if_a <: if_b)
7014 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07007015 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
7016 << ") extends "
7017 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07007018 << "interface list.";
7019 }
7020 }
7021 }
7022 return filled_ifcount;
7023}
7024
7025bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
7026 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
7027 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08007028 const bool has_superclass = klass->HasSuperClass();
7029 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007030 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007031 const size_t num_interfaces =
7032 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007033 if (num_interfaces == 0) {
7034 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08007035 if (LIKELY(has_superclass)) {
7036 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
7037 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007038 // Class implements no interfaces.
7039 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007040 return true;
7041 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007042 // Class implements same interfaces as parent, are any of these not marker interfaces?
7043 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007044 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007045 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007046 if (super_iftable->GetMethodArrayCount(i) > 0) {
7047 has_non_marker_interface = true;
7048 break;
7049 }
7050 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007051 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07007052 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007053 klass->SetIfTable(super_iftable);
7054 return true;
7055 }
7056 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007057 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07007058 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007059 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007060 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007061 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00007062 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007063 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007064 if (UNLIKELY(!interface->IsInterface())) {
7065 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007066 ThrowIncompatibleClassChangeError(klass.Get(),
7067 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07007068 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007069 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7070 return false;
7071 }
7072 ifcount += interface->GetIfTableCount();
7073 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007074 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007075 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007076 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007077 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007078 return false;
7079 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007080 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007081 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007082 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007083 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007084 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007085 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007086 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007087 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007088
7089 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7090 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7091 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007092 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007093
7094 size_t new_ifcount;
7095 {
Mathieu Chartier268764d2016-09-13 12:09:38 -07007096 ScopedAssertNoThreadSuspension nts("Copying mirror::Class*'s for FillIfTable");
Vladimir Markobcf17522018-06-01 13:14:32 +01007097 std::vector<ObjPtr<mirror::Class>> to_add;
Alex Lighteb7c1442015-08-31 13:17:42 -07007098 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007099 ObjPtr<mirror::Class> interface = have_interfaces ? interfaces->Get(i) :
Vladimir Marko19a4d372016-12-08 14:41:46 +00007100 mirror::Class::GetDirectInterface(self, klass.Get(), i);
Vladimir Markobcf17522018-06-01 13:14:32 +01007101 to_add.push_back(interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007102 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007103
7104 new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007105 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007106
Ian Rogers7b078e82014-09-10 14:44:24 -07007107 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007108
Ian Rogersb52b01a2012-01-12 17:01:38 -08007109 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007110 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007111 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007112 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Alex Lighteb7c1442015-08-31 13:17:42 -07007113 iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007114 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007115 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007116 return false;
7117 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007118 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007119 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007120 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007121 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007122 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007123 return true;
7124}
7125
Alex Light1f3925d2016-09-07 12:04:20 -07007126// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7127// of methods must be unique.
7128static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7129 return nullptr;
7130}
7131
7132template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007133static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007134 const ScopedArenaVector<ArtMethod*>& list,
7135 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007136 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007137 for (ArtMethod* method : list) {
7138 if (cmp.HasSameNameAndSignature(method)) {
7139 return method;
7140 }
7141 }
Alex Light1f3925d2016-09-07 12:04:20 -07007142 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007143}
7144
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007145namespace {
7146
Alex Light1f3925d2016-09-07 12:04:20 -07007147// Check that all vtable entries are present in this class's virtuals or are the same as a
7148// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007149void CheckClassOwnsVTableEntries(Thread* self,
7150 Handle<mirror::Class> klass,
7151 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007152 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007153 StackHandleScope<2> hs(self);
7154 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007155 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007156 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007157 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007158 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7159 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7160 CHECK(m != nullptr);
7161
Alex Lighta41a30782017-03-29 11:33:19 -07007162 if (m->GetMethodIndexDuringLinking() != i) {
7163 LOG(WARNING) << m->PrettyMethod()
7164 << " has an unexpected method index for its spot in the vtable for class"
7165 << klass->PrettyClass();
7166 }
Alex Lighte64300b2015-12-15 15:02:47 -08007167 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7168 auto is_same_method = [m] (const ArtMethod& meth) {
7169 return &meth == m;
7170 };
Alex Light3f980532017-03-17 15:10:32 -07007171 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7172 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7173 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7174 << klass->PrettyClass() << " or any of its superclasses!";
7175 }
Alex Lighte64300b2015-12-15 15:02:47 -08007176 }
7177}
7178
Alex Light1f3925d2016-09-07 12:04:20 -07007179// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7180// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007181template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007182void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007183 REQUIRES_SHARED(Locks::mutator_lock_) {
7184 StackHandleScope<1> hs(self);
7185 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7186 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007187
7188 // Observations:
7189 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7190 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7191 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7192 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7193 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7194 // * The single-pass algorithm will trade memory for speed, but that is OK.
7195
7196 CHECK_GT(num_entries, 0);
7197
7198 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7199 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7200 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7201 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7202 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7203 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7204 << m2->PrettyMethod() << " (0x" << std::hex
7205 << reinterpret_cast<uintptr_t>(m2) << ")";
7206 };
7207 struct BaseHashType {
7208 static size_t HashCombine(size_t seed, size_t val) {
7209 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7210 }
7211 };
7212
7213 // Check assuming all entries come from the same dex file.
7214 {
7215 // Find the first interesting method and its dex file.
7216 int32_t start = 0;
7217 for (; start < num_entries; ++start) {
7218 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7219 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7220 // maybe).
7221 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7222 vtable_entry->GetAccessFlags())) {
7223 continue;
7224 }
7225 break;
7226 }
7227 if (start == num_entries) {
7228 return;
7229 }
7230 const DexFile* dex_file =
7231 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7232 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7233
7234 // Helper function to avoid logging if we have to run the cross-file checks.
7235 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7236 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7237 using PairType = std::pair<uint32_t, uint16_t>;
7238 struct PairHash : BaseHashType {
7239 size_t operator()(const PairType& key) const {
7240 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7241 }
7242 };
7243 std::unordered_map<PairType, int32_t, PairHash> seen;
7244 seen.reserve(2 * num_entries);
7245 bool need_slow_path = false;
7246 bool found_dup = false;
7247 for (int i = start; i < num_entries; ++i) {
7248 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7249 // wrt/ kPointerSize.
7250 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7251 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7252 vtable_entry->GetAccessFlags())) {
7253 continue;
7254 }
7255 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7256 if (dex_file != m->GetDexFile()) {
7257 need_slow_path = true;
7258 break;
7259 }
7260 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7261 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7262 auto it = seen.find(pair);
7263 if (it != seen.end()) {
7264 found_dup = true;
7265 if (log_warn) {
7266 log_fn(it->second, i);
7267 }
7268 } else {
7269 seen.emplace(pair, i);
7270 }
7271 }
7272 return std::make_pair(need_slow_path, found_dup);
7273 };
7274 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7275 if (!result.first) {
7276 if (result.second) {
7277 check_fn(/* log_warn= */ true);
7278 }
7279 return;
7280 }
7281 }
7282
7283 // Need to check across dex files.
7284 struct Entry {
7285 size_t cached_hash = 0;
7286 const char* name = nullptr;
7287 Signature signature = Signature::NoSignature();
7288 uint32_t name_len = 0;
7289
7290 Entry(const DexFile* dex_file, const dex::MethodId& mid)
7291 : name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
7292 signature(dex_file->GetMethodSignature(mid)) {
7293 }
7294
7295 bool operator==(const Entry& other) const {
7296 if (name_len != other.name_len || strcmp(name, other.name) != 0) {
7297 return false;
7298 }
7299 return signature == other.signature;
7300 }
7301 };
7302 struct EntryHash {
7303 size_t operator()(const Entry& key) const {
7304 return key.cached_hash;
7305 }
7306 };
7307 std::unordered_map<Entry, int32_t, EntryHash> map;
7308 for (int32_t i = 0; i < num_entries; ++i) {
7309 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7310 // wrt/ kPointerSize.
7311 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7312 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7313 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007314 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7315 vtable_entry->GetAccessFlags())) {
7316 continue;
7317 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007318 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7319 const DexFile* dex_file = m->GetDexFile();
7320 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7321
7322 Entry e(dex_file, mid);
7323
7324 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7325 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7326 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7327 sig_hash);
7328
7329 auto it = map.find(e);
7330 if (it != map.end()) {
7331 log_fn(it->second, i);
7332 } else {
7333 map.emplace(e, i);
Alex Light1f3925d2016-09-07 12:04:20 -07007334 }
7335 }
7336}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007337
7338void CheckVTableHasNoDuplicates(Thread* self,
7339 Handle<mirror::Class> klass,
7340 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007341 REQUIRES_SHARED(Locks::mutator_lock_) {
7342 switch (pointer_size) {
7343 case PointerSize::k64:
7344 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7345 break;
7346 case PointerSize::k32:
7347 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7348 break;
7349 }
7350}
Alex Light1f3925d2016-09-07 12:04:20 -07007351
7352static void SanityCheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
7353 REQUIRES_SHARED(Locks::mutator_lock_) {
7354 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7355 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7356}
7357
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007358} // namespace
7359
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007360void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7361 ArtMethod* unimplemented_method,
7362 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007363 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007364 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007365 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007366 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007367 if (super_class->ShouldHaveImt()) {
7368 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7369 for (size_t i = 0; i < ImTable::kSize; ++i) {
7370 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007371 }
7372 } else {
7373 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007374 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007375 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007376 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007377 FillIMTFromIfTable(if_table,
7378 unimplemented_method,
7379 imt_conflict_method,
7380 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007381 /*create_conflict_tables=*/false,
7382 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007383 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007384 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007385 }
7386 }
7387}
7388
Vladimir Marko921094a2017-01-12 18:37:06 +00007389class ClassLinker::LinkInterfaceMethodsHelper {
7390 public:
7391 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7392 Handle<mirror::Class> klass,
7393 Thread* self,
7394 Runtime* runtime)
7395 : class_linker_(class_linker),
7396 klass_(klass),
7397 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7398 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7399 self_(self),
7400 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7401 allocator_(&stack_),
7402 default_conflict_methods_(allocator_.Adapter()),
7403 overriding_default_conflict_methods_(allocator_.Adapter()),
7404 miranda_methods_(allocator_.Adapter()),
7405 default_methods_(allocator_.Adapter()),
7406 overriding_default_methods_(allocator_.Adapter()),
7407 move_table_(allocator_.Adapter()) {
7408 }
7409
7410 ArtMethod* FindMethod(ArtMethod* interface_method,
7411 MethodNameAndSignatureComparator& interface_name_comparator,
7412 ArtMethod* vtable_impl)
7413 REQUIRES_SHARED(Locks::mutator_lock_);
7414
7415 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7416 MethodNameAndSignatureComparator& interface_name_comparator)
7417 REQUIRES_SHARED(Locks::mutator_lock_);
7418
7419 bool HasNewVirtuals() const {
7420 return !(miranda_methods_.empty() &&
7421 default_methods_.empty() &&
7422 overriding_default_methods_.empty() &&
7423 overriding_default_conflict_methods_.empty() &&
7424 default_conflict_methods_.empty());
7425 }
7426
7427 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7428
7429 ObjPtr<mirror::PointerArray> UpdateVtable(
7430 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7431 ObjPtr<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
7432
7433 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7434
7435 void UpdateIMT(ArtMethod** out_imt);
7436
7437 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7438 if (kIsDebugBuild) {
7439 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7440 // Check that there are no stale methods are in the dex cache array.
7441 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7442 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007443 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7444 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007445 CHECK(move_table_.find(m) == move_table_.end() ||
7446 // The original versions of copied methods will still be present so allow those too.
7447 // Note that if the first check passes this might fail to GetDeclaringClass().
7448 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7449 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7450 [m] (ArtMethod& meth) {
7451 return &meth == m;
7452 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7453 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7454 }
7455 }
7456 }
7457
7458 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7459 LengthPrefixedArray<ArtMethod>* methods) {
7460 if (kIsDebugBuild) {
7461 CHECK(methods != nullptr);
7462 // Put some random garbage in old methods to help find stale pointers.
7463 if (methods != old_methods && old_methods != nullptr) {
7464 // Need to make sure the GC is not running since it could be scanning the methods we are
7465 // about to overwrite.
7466 ScopedThreadStateChange tsc(self_, kSuspended);
7467 gc::ScopedGCCriticalSection gcs(self_,
7468 gc::kGcCauseClassLinker,
7469 gc::kCollectorTypeClassLinker);
7470 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7471 method_size_,
7472 method_alignment_);
7473 memset(old_methods, 0xFEu, old_size);
7474 }
7475 }
7476 }
7477
7478 private:
7479 size_t NumberOfNewVirtuals() const {
7480 return miranda_methods_.size() +
7481 default_methods_.size() +
7482 overriding_default_conflict_methods_.size() +
7483 overriding_default_methods_.size() +
7484 default_conflict_methods_.size();
7485 }
7486
7487 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7488 return !klass_->IsInterface();
7489 }
7490
7491 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7492 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7493 << "Interfaces should only have default-conflict methods appended to them.";
7494 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7495 << miranda_methods_.size()
7496 << " default_methods=" << default_methods_.size()
7497 << " overriding_default_methods=" << overriding_default_methods_.size()
7498 << " default_conflict_methods=" << default_conflict_methods_.size()
7499 << " overriding_default_conflict_methods="
7500 << overriding_default_conflict_methods_.size();
7501 }
7502
7503 ClassLinker* class_linker_;
7504 Handle<mirror::Class> klass_;
7505 size_t method_alignment_;
7506 size_t method_size_;
7507 Thread* const self_;
7508
7509 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7510 // the virtual methods array.
7511 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7512 // during cross compilation.
7513 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7514 ArenaStack stack_;
7515 ScopedArenaAllocator allocator_;
7516
7517 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7518 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7519 ScopedArenaVector<ArtMethod*> miranda_methods_;
7520 ScopedArenaVector<ArtMethod*> default_methods_;
7521 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7522
7523 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7524};
7525
7526ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7527 ArtMethod* interface_method,
7528 MethodNameAndSignatureComparator& interface_name_comparator,
7529 ArtMethod* vtable_impl) {
7530 ArtMethod* current_method = nullptr;
7531 switch (class_linker_->FindDefaultMethodImplementation(self_,
7532 interface_method,
7533 klass_,
7534 /*out*/&current_method)) {
7535 case DefaultMethodSearchResult::kDefaultConflict: {
7536 // Default method conflict.
7537 DCHECK(current_method == nullptr);
7538 ArtMethod* default_conflict_method = nullptr;
7539 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7540 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7541 default_conflict_method = vtable_impl;
7542 } else {
7543 // See if we already have a conflict method for this method.
7544 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7545 interface_name_comparator,
7546 default_conflict_methods_,
7547 overriding_default_conflict_methods_);
7548 if (LIKELY(preexisting_conflict != nullptr)) {
7549 // We already have another conflict we can reuse.
7550 default_conflict_method = preexisting_conflict;
7551 } else {
7552 // Note that we do this even if we are an interface since we need to create this and
7553 // cannot reuse another classes.
7554 // Create a new conflict method for this to use.
7555 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7556 new(default_conflict_method) ArtMethod(interface_method,
7557 class_linker_->GetImagePointerSize());
7558 if (vtable_impl == nullptr) {
7559 // Save the conflict method. We need to add it to the vtable.
7560 default_conflict_methods_.push_back(default_conflict_method);
7561 } else {
7562 // Save the conflict method but it is already in the vtable.
7563 overriding_default_conflict_methods_.push_back(default_conflict_method);
7564 }
7565 }
7566 }
7567 current_method = default_conflict_method;
7568 break;
7569 } // case kDefaultConflict
7570 case DefaultMethodSearchResult::kDefaultFound: {
7571 DCHECK(current_method != nullptr);
7572 // Found a default method.
7573 if (vtable_impl != nullptr &&
7574 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7575 // We found a default method but it was the same one we already have from our
7576 // superclass. Don't bother adding it to our vtable again.
7577 current_method = vtable_impl;
7578 } else if (LIKELY(FillTables())) {
7579 // Interfaces don't need to copy default methods since they don't have vtables.
7580 // Only record this default method if it is new to save space.
7581 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7582 // would make lookup for interface super much faster. (We would only need to scan
7583 // the iftable to find if there is a NSME or AME.)
7584 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7585 default_methods_,
7586 overriding_default_methods_);
7587 if (old == nullptr) {
7588 // We found a default method implementation and there were no conflicts.
7589 if (vtable_impl == nullptr) {
7590 // Save the default method. We need to add it to the vtable.
7591 default_methods_.push_back(current_method);
7592 } else {
7593 // Save the default method but it is already in the vtable.
7594 overriding_default_methods_.push_back(current_method);
7595 }
7596 } else {
7597 CHECK(old == current_method) << "Multiple default implementations selected!";
7598 }
7599 }
7600 break;
7601 } // case kDefaultFound
7602 case DefaultMethodSearchResult::kAbstractFound: {
7603 DCHECK(current_method == nullptr);
7604 // Abstract method masks all defaults.
7605 if (vtable_impl != nullptr &&
7606 vtable_impl->IsAbstract() &&
7607 !vtable_impl->IsDefaultConflicting()) {
7608 // We need to make this an abstract method but the version in the vtable already is so
7609 // don't do anything.
7610 current_method = vtable_impl;
7611 }
7612 break;
7613 } // case kAbstractFound
7614 }
7615 return current_method;
7616}
7617
7618ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7619 ArtMethod* interface_method,
7620 MethodNameAndSignatureComparator& interface_name_comparator) {
7621 // Find out if there is already a miranda method we can use.
7622 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7623 miranda_methods_);
7624 if (miranda_method == nullptr) {
7625 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7626 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7627 CHECK(miranda_method != nullptr);
7628 // Point the interface table at a phantom slot.
7629 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7630 miranda_methods_.push_back(miranda_method);
7631 }
7632 return miranda_method;
7633}
7634
7635void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7636 LogNewVirtuals();
7637
7638 const size_t old_method_count = klass_->NumMethods();
7639 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7640 DCHECK_NE(old_method_count, new_method_count);
7641
7642 // Attempt to realloc to save RAM if possible.
7643 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7644 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7645 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7646 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7647 // CopyFrom has internal read barriers.
7648 //
7649 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7650 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7651 method_size_,
7652 method_alignment_);
7653 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7654 method_size_,
7655 method_alignment_);
7656 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7657 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007658 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007659 self_, old_methods, old_methods_ptr_size, new_size));
7660 CHECK(methods != nullptr); // Native allocation failure aborts.
7661
7662 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7663 if (methods != old_methods) {
7664 // Maps from heap allocated miranda method to linear alloc miranda method.
7665 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7666 // Copy over the old methods.
7667 for (auto& m : klass_->GetMethods(pointer_size)) {
7668 move_table_.emplace(&m, &*out);
7669 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7670 // barriers when it copies.
7671 out->CopyFrom(&m, pointer_size);
7672 ++out;
7673 }
7674 }
7675 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7676 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7677 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007678 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7679 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007680 ArtMethod& new_method = *out;
7681 new_method.CopyFrom(mir_method, pointer_size);
7682 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7683 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7684 << "Miranda method should be abstract!";
7685 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007686 // Update the entry in the method array, as the array will be used for future lookups,
7687 // where thread suspension is allowed.
7688 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7689 // would not see them.
7690 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007691 ++out;
7692 }
7693 // We need to copy the default methods into our own method table since the runtime requires that
7694 // every method on a class's vtable be in that respective class's virtual method table.
7695 // NOTE This means that two classes might have the same implementation of a method from the same
7696 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7697 // default method found on a class with one found on the declaring interface directly and must
7698 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007699 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7700 &overriding_default_methods_}) {
7701 for (size_t i = 0; i < methods_vec->size(); ++i) {
7702 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007703 ArtMethod& new_method = *out;
7704 new_method.CopyFrom(def_method, pointer_size);
7705 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7706 // verified yet it shouldn't have methods that are skipping access checks.
7707 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7708 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007709 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007710 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7711 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7712 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7713 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007714 // Update the entry in the method array, as the array will be used for future lookups,
7715 // where thread suspension is allowed.
7716 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7717 // would not see them.
7718 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007719 ++out;
7720 }
7721 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007722 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7723 &overriding_default_conflict_methods_}) {
7724 for (size_t i = 0; i < methods_vec->size(); ++i) {
7725 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007726 ArtMethod& new_method = *out;
7727 new_method.CopyFrom(conf_method, pointer_size);
7728 // This is a type of default method (there are default method impls, just a conflict) so
7729 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7730 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7731 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007732 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
7733 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007734 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007735 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007736 constexpr uint32_t kMaskFlags =
7737 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00007738 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7739 DCHECK(new_method.IsDefaultConflicting());
7740 // The actual method might or might not be marked abstract since we just copied it from a
7741 // (possibly default) interface method. We need to set it entry point to be the bridge so
7742 // that the compiler will not invoke the implementation of whatever method we copied from.
7743 EnsureThrowsInvocationError(class_linker_, &new_method);
7744 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007745 // Update the entry in the method array, as the array will be used for future lookups,
7746 // where thread suspension is allowed.
7747 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7748 // would not see them.
7749 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007750 ++out;
7751 }
7752 }
7753 methods->SetSize(new_method_count);
7754 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7755}
7756
7757ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
7758 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
7759 ObjPtr<mirror::PointerArray> old_vtable) {
7760 // Update the vtable to the new method structures. We can skip this for interfaces since they
7761 // do not have vtables.
7762 const size_t old_vtable_count = old_vtable->GetLength();
7763 const size_t new_vtable_count = old_vtable_count +
7764 miranda_methods_.size() +
7765 default_methods_.size() +
7766 default_conflict_methods_.size();
7767
7768 ObjPtr<mirror::PointerArray> vtable =
Vladimir Markobcf17522018-06-01 13:14:32 +01007769 ObjPtr<mirror::PointerArray>::DownCast(old_vtable->CopyOf(self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007770 if (UNLIKELY(vtable == nullptr)) {
7771 self_->AssertPendingOOMException();
7772 return nullptr;
7773 }
7774
7775 size_t vtable_pos = old_vtable_count;
7776 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7777 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7778 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7779 default_conflict_methods_,
7780 miranda_methods_}) {
7781 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007782 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007783 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7784 // fields are references into the dex file the method was defined in. Since the ArtMethod
7785 // does not store that information it uses declaring_class_->dex_cache_.
7786 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7787 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7788 ++vtable_pos;
7789 }
7790 }
7791 DCHECK_EQ(vtable_pos, new_vtable_count);
7792
7793 // Update old vtable methods. We use the default_translations map to figure out what each
7794 // vtable entry should be updated to, if they need to be at all.
7795 for (size_t i = 0; i < old_vtable_count; ++i) {
7796 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7797 // Try and find what we need to change this method to.
7798 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007799 if (translation_it != default_translations.end()) {
7800 if (translation_it->second.IsInConflict()) {
7801 // Find which conflict method we are to use for this method.
7802 MethodNameAndSignatureComparator old_method_comparator(
7803 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7804 // We only need to look through overriding_default_conflict_methods since this is an
7805 // overridden method we are fixing up here.
7806 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7807 old_method_comparator, overriding_default_conflict_methods_);
7808 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7809 translated_method = new_conflict_method;
7810 } else if (translation_it->second.IsAbstract()) {
7811 // Find which miranda method we are to use for this method.
7812 MethodNameAndSignatureComparator old_method_comparator(
7813 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7814 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
7815 miranda_methods_);
7816 DCHECK(miranda_method != nullptr);
7817 translated_method = miranda_method;
7818 } else {
7819 // Normal default method (changed from an older default or abstract interface method).
7820 DCHECK(translation_it->second.IsTranslation());
7821 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007822 auto it = move_table_.find(translated_method);
7823 DCHECK(it != move_table_.end());
7824 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00007825 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007826 } else {
7827 auto it = move_table_.find(translated_method);
7828 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00007829 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007830
7831 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007832 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007833 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007834 if (kIsDebugBuild) {
7835 auto* methods = klass_->GetMethodsPtr();
7836 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007837 reinterpret_cast<uintptr_t>(translated_method));
7838 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00007839 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
7840 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007841 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007842 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007843 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007844 }
7845 }
Vladimir Markod93e3742018-07-18 10:58:13 +01007846 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00007847 return vtable;
7848}
7849
7850void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
7851 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7852 const size_t ifcount = klass_->GetIfTableCount();
7853 // Go fix up all the stale iftable pointers.
7854 for (size_t i = 0; i < ifcount; ++i) {
7855 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
Vladimir Marko557fece2019-03-26 14:29:41 +00007856 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArray(i);
7857 ArtMethod* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00007858 DCHECK(m != nullptr) << klass_->PrettyClass();
7859 auto it = move_table_.find(m);
7860 if (it != move_table_.end()) {
7861 auto* new_m = it->second;
7862 DCHECK(new_m != nullptr) << klass_->PrettyClass();
7863 method_array->SetElementPtrSize(j, new_m, pointer_size);
7864 }
7865 }
7866 }
7867}
7868
7869void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
7870 // Fix up IMT next.
7871 for (size_t i = 0; i < ImTable::kSize; ++i) {
7872 auto it = move_table_.find(out_imt[i]);
7873 if (it != move_table_.end()) {
7874 out_imt[i] = it->second;
7875 }
7876 }
7877}
7878
Alex Light705ad492015-09-21 11:36:30 -07007879// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07007880bool ClassLinker::LinkInterfaceMethods(
7881 Thread* self,
7882 Handle<mirror::Class> klass,
Alex Light9139e002015-10-09 15:59:48 -07007883 const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007884 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07007885 ArtMethod** out_imt) {
7886 StackHandleScope<3> hs(self);
7887 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07007888
7889 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07007890 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07007891 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07007892 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07007893 const size_t ifcount = klass->GetIfTableCount();
7894
Vladimir Marko921094a2017-01-12 18:37:06 +00007895 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007896
7897 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7898 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07007899 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007900 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07007901 const bool extend_super_iftable = has_superclass;
7902 if (has_superclass && fill_tables) {
7903 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07007904 unimplemented_method,
7905 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007906 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007907 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007908 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07007909 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
7910 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07007911 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007912 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
7913 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07007914 }
7915 }
7916
Vladimir Marko921094a2017-01-12 18:37:06 +00007917 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
7918
Igor Murashkinb1d8c312015-08-04 11:18:43 -07007919 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007920 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07007921 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
7922 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
7923 // they will already be null. This has the additional benefit that the declarer of a miranda
7924 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01007925 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07007926 --i;
Alex Light9139e002015-10-09 15:59:48 -07007927 DCHECK_LT(i, ifcount);
7928
Alex Light705ad492015-09-21 11:36:30 -07007929 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007930 if (num_methods > 0) {
7931 StackHandleScope<2> hs2(self);
7932 const bool is_super = i < super_ifcount;
7933 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07007934 // We don't actually create or fill these tables for interfaces, we just copy some methods for
7935 // conflict methods. Just set this as nullptr in those cases.
7936 Handle<mirror::PointerArray> method_array(fill_tables
7937 ? hs2.NewHandle(iftable->GetMethodArray(i))
7938 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07007939
Alex Lighte64300b2015-12-15 15:02:47 -08007940 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08007941 ScopedNullHandle<mirror::PointerArray> null_handle;
7942 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007943 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007944
Alex Light9139e002015-10-09 15:59:48 -07007945 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
7946 // and confusing. Default methods should always look through all the superclasses
7947 // because they are the last choice of an implementation. We get around this by looking
7948 // at the super-classes iftable methods (copied into method_array previously) when we are
7949 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08007950 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07007951 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08007952 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07007953 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08007954 using_virtuals = true;
7955 input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
7956 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07007957 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08007958 // For a new interface, however, we need the whole vtable in case a new
7959 // interface method is implemented in the whole superclass.
7960 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007961 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007962 input_vtable_array = vtable;
7963 input_array_length = input_vtable_array->GetLength();
7964 }
Alex Lighte64300b2015-12-15 15:02:47 -08007965
Alex Lighteb7c1442015-08-31 13:17:42 -07007966 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08007967 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007968 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007969 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07007970 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00007971 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07007972 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07007973 // For each method listed in the interface's method list, find the
7974 // matching method in our class's method list. We want to favor the
7975 // subclass over the superclass, which just requires walking
7976 // back from the end of the vtable. (This only matters if the
7977 // superclass defines a private method and this class redefines
7978 // it -- otherwise it would use the same vtable slot. In .dex files
7979 // those don't end up in the virtual method table, so it shouldn't
7980 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07007981 //
7982 // To find defaults we need to do the same but also go over interfaces.
7983 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07007984 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007985 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08007986 ArtMethod* vtable_method = using_virtuals ?
7987 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07007988 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
7989 ArtMethod* vtable_method_for_name_comparison =
7990 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07007991 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07007992 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007993 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07007994 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
7995 // allocations.
7996 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07007997 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07007998 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07007999 vtable_method->PrettyMethod().c_str(),
8000 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07008001 return false;
Alex Light9139e002015-10-09 15:59:48 -07008002 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07008003 // We might have a newer, better, default method for this, so we just skip it. If we
8004 // are still using this we will select it again when scanning for default methods. To
8005 // obviate the need to copy the method again we will make a note that we already found
8006 // a default here.
8007 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07008008 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07008009 break;
8010 } else {
8011 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07008012 if (LIKELY(fill_tables)) {
8013 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
8014 // Place method in imt if entry is empty, place conflict otherwise.
8015 SetIMTRef(unimplemented_method,
8016 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07008017 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008018 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07008019 /*out*/imt_ptr);
8020 }
Ian Rogers9bc81912012-10-11 21:43:36 -07008021 break;
8022 }
8023 }
Alex Light9139e002015-10-09 15:59:48 -07008024 }
8025 // Continue on to the next method if we are done.
8026 if (LIKELY(found_impl)) {
8027 continue;
8028 } else if (LIKELY(super_interface)) {
8029 // Don't look for a default implementation when the super-method is implemented directly
8030 // by the class.
8031 //
8032 // See if we can use the superclasses method and skip searching everything else.
8033 // Note: !found_impl && super_interface
8034 CHECK(extend_super_iftable);
8035 // If this is a super_interface method it is possible we shouldn't override it because a
8036 // superclass could have implemented it directly. We get the method the superclass used
8037 // to implement this to know if we can override it with a default method. Doing this is
8038 // safe since we know that the super_iftable is filled in so we can simply pull it from
8039 // there. We don't bother if this is not a super-classes interface since in that case we
8040 // have scanned the entire vtable anyway and would have found it.
8041 // TODO This is rather dirty but it is faster than searching through the entire vtable
8042 // every time.
8043 ArtMethod* supers_method =
8044 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
8045 DCHECK(supers_method != nullptr);
8046 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07008047 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07008048 // The method is not overridable by a default method (i.e. it is directly implemented
8049 // in some class). Therefore move onto the next interface method.
8050 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008051 } else {
8052 // If the super-classes method is override-able by a default method we need to keep
8053 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
8054 // 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 -07008055 // to the vtable twice, causing corruption (vtable entries having inconsistent and
8056 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
8057 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008058 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07008059 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
8060 << " and not 'nullptr' or "
8061 << supers_method->PrettyMethod()
8062 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008063 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07008064 }
8065 }
8066 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00008067 ArtMethod* current_method = helper.FindMethod(interface_method,
8068 interface_name_comparator,
8069 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008070 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008071 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008072 // We could not find an implementation for this method and since it is a brand new
8073 // interface we searched the entire vtable (and all default methods) for an
8074 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00008075 current_method = helper.GetOrCreateMirandaMethod(interface_method,
8076 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008077 }
8078
8079 if (current_method != nullptr) {
8080 // We found a default method implementation. Record it in the iftable and IMT.
8081 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
8082 SetIMTRef(unimplemented_method,
8083 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08008084 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008085 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08008086 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008087 }
8088 }
Alex Light705ad492015-09-21 11:36:30 -07008089 } // For each method in interface end.
8090 } // if (num_methods > 0)
8091 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008092 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008093 if (helper.HasNewVirtuals()) {
8094 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8095 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8096 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8097
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008098 // 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 -07008099 // suspension assert.
8100 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008101
Alex Light705ad492015-09-21 11:36:30 -07008102 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008103 vtable.Assign(helper.UpdateVtable(default_translations, vtable.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008104 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008105 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008106 return false;
8107 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008108 helper.UpdateIfTable(iftable);
8109 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008110 }
Alex Light705ad492015-09-21 11:36:30 -07008111
Vladimir Marko921094a2017-01-12 18:37:06 +00008112 helper.CheckNoStaleMethodsInDexCache();
8113 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008114 } else {
8115 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008116 }
Alex Light705ad492015-09-21 11:36:30 -07008117 if (kIsDebugBuild && !is_interface) {
Alex Light1f3925d2016-09-07 12:04:20 -07008118 SanityCheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008119 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008120 return true;
8121}
8122
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008123bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008124 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008125 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008126}
8127
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008128bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008129 CHECK(klass != nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008130 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008131}
8132
Brian Carlstromdbc05252011-09-09 01:59:59 -07008133struct LinkFieldsComparator {
Igor Murashkin2ffb7032017-11-08 13:35:21 -08008134 LinkFieldsComparator() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07008135 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07008136 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008137 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08008138 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07008139 // 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 -07008140 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
8141 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08008142 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00008143 if (type1 == Primitive::kPrimNot) {
8144 // Reference always goes first.
8145 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08008146 }
Vladimir Markod5777482014-11-12 17:02:02 +00008147 if (type2 == Primitive::kPrimNot) {
8148 // Reference always goes first.
8149 return false;
8150 }
8151 size_t size1 = Primitive::ComponentSize(type1);
8152 size_t size2 = Primitive::ComponentSize(type2);
8153 if (size1 != size2) {
8154 // Larger primitive types go first.
8155 return size1 > size2;
8156 }
8157 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
8158 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008159 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008160 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
8161 // by name and for equal names by type id index.
8162 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
8163 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07008164 }
8165};
8166
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008167bool ClassLinker::LinkFields(Thread* self,
8168 Handle<mirror::Class> klass,
8169 bool is_static,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008170 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008171 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008172 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008173 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8174 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008175
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008176 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008177 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008178 if (is_static) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008179 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008180 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008181 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008182 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008183 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008184 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008185 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008186 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008187 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008188
David Sehr709b0702016-10-13 09:12:37 -07008189 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008190
Brian Carlstromdbc05252011-09-09 01:59:59 -07008191 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008192 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008193 //
8194 // The overall sort order order is:
8195 // 1) All object reference fields, sorted alphabetically.
8196 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8197 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8198 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8199 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8200 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8201 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8202 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8203 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8204 //
8205 // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
8206 // in the memory layout of the structure. See ShuffleForward for how this is done.
Mathieu Chartierc7853442015-03-27 14:35:38 -07008207 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008208 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07008209 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07008210 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008211 grouped_and_sorted_fields.push_back(&fields->At(i));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008212 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07008213 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
8214 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07008215
Fred Shih381e4ca2014-08-25 17:24:27 -07008216 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07008217 size_t current_field = 0;
8218 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07008219 FieldGaps gaps;
8220
Brian Carlstromdbc05252011-09-09 01:59:59 -07008221 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07008222 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07008223 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07008224 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07008225 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07008226 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008227 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008228 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
8229 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07008230 MemberOffset old_offset = field_offset;
8231 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
8232 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
8233 }
Roland Levillain14d90572015-07-16 10:52:26 +01008234 DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
Brian Carlstromdbc05252011-09-09 01:59:59 -07008235 grouped_and_sorted_fields.pop_front();
8236 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008237 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00008238 field_offset = MemberOffset(field_offset.Uint32Value() +
8239 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008240 }
Fred Shih381e4ca2014-08-25 17:24:27 -07008241 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
8242 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00008243 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8244 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8245 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
8246 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07008247 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
8248 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07008249 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008250
Elliott Hughesadb460d2011-10-05 17:02:34 -07008251 // 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 -07008252 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008253 // We know there are no non-reference fields in the Reference classes, and we know
8254 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008255 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008256 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008257 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008258 --num_reference_fields;
8259 }
8260
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008261 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008262 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008263 if (is_static) {
8264 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008265 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008266 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008267 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008268 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008269 if (num_reference_fields == 0 || super_class == nullptr) {
8270 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008271 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008272 if (super_class == nullptr ||
8273 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8274 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008275 }
8276 }
8277 if (kIsDebugBuild) {
8278 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8279 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008280 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008281 while (cur_super != nullptr) {
8282 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8283 cur_super = cur_super->GetSuperClass();
8284 }
8285 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008286 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008287 } else {
8288 // Check that there is at least num_reference_fields other than Object.class.
8289 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008290 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008291 }
8292 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008293 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008294 std::string temp;
8295 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8296 size_t previous_size = klass->GetObjectSize();
8297 if (previous_size != 0) {
8298 // Make sure that we didn't originally have an incorrect size.
8299 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008300 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008301 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008302 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008303 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008304
8305 if (kIsDebugBuild) {
8306 // Make sure that the fields array is ordered by name but all reference
8307 // offsets are at the beginning as far as alignment allows.
8308 MemberOffset start_ref_offset = is_static
Mathieu Chartiere401d142015-04-22 13:56:20 -07008309 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008310 : klass->GetFirstReferenceInstanceFieldOffset();
8311 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8312 num_reference_fields *
8313 sizeof(mirror::HeapReference<mirror::Object>));
8314 MemberOffset current_ref_offset = start_ref_offset;
8315 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008316 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008317 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008318 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8319 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008320 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008321 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008322 // NOTE: The field names can be the same. This is not possible in the Java language
8323 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008324 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008325 }
8326 Primitive::Type type = field->GetTypeAsPrimitiveType();
8327 bool is_primitive = type != Primitive::kPrimNot;
8328 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8329 strcmp("referent", field->GetName()) == 0) {
8330 is_primitive = true; // We lied above, so we have to expect a lie here.
8331 }
8332 MemberOffset offset = field->GetOffsetDuringLinking();
8333 if (is_primitive) {
8334 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8335 // Shuffled before references.
8336 size_t type_size = Primitive::ComponentSize(type);
8337 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8338 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8339 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8340 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8341 }
8342 } else {
8343 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8344 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8345 sizeof(mirror::HeapReference<mirror::Object>));
8346 }
8347 }
8348 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8349 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008350 return true;
8351}
8352
Vladimir Marko76649e82014-11-10 18:32:59 +00008353// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008354void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008355 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008356 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008357 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008358 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008359 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008360 // Compute reference offsets unless our superclass overflowed.
8361 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8362 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008363 if (num_reference_fields != 0u) {
8364 // All of the fields that contain object references are guaranteed be grouped in memory
8365 // starting at an appropriately aligned address after super class object data.
8366 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8367 sizeof(mirror::HeapReference<mirror::Object>));
8368 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008369 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008370 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008371 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008372 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008373 reference_offsets |= (0xffffffffu << start_bit) &
8374 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008375 }
8376 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008377 }
8378 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008379 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008380}
8381
Vladimir Marko18090d12018-06-01 16:53:12 +01008382ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8383 ObjPtr<mirror::DexCache> dex_cache) {
8384 StackHandleScope<1> hs(Thread::Current());
8385 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8386 return DoResolveString(string_idx, h_dex_cache);
8387}
8388
8389ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8390 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008391 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008392 uint32_t utf16_length;
8393 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008394 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008395 if (string != nullptr) {
8396 dex_cache->SetResolvedString(string_idx, string);
8397 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008398 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008399}
8400
Vladimir Marko18090d12018-06-01 16:53:12 +01008401ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8402 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008403 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008404 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008405 uint32_t utf16_length;
8406 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008407 ObjPtr<mirror::String> string =
8408 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008409 if (string != nullptr) {
8410 dex_cache->SetResolvedString(string_idx, string);
8411 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008412 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008413}
8414
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008415ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008416 ObjPtr<mirror::Class> referrer) {
8417 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8418}
8419
8420ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008421 ObjPtr<mirror::DexCache> dex_cache,
8422 ObjPtr<mirror::ClassLoader> class_loader) {
8423 const DexFile& dex_file = *dex_cache->GetDexFile();
8424 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8425 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8426 ObjPtr<mirror::Class> type = nullptr;
8427 if (descriptor[1] == '\0') {
8428 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8429 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008430 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008431 } else {
8432 Thread* const self = Thread::Current();
8433 DCHECK(self != nullptr);
8434 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8435 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008436 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008437 }
8438 if (type != nullptr) {
8439 if (type->IsResolved()) {
8440 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008441 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008442 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008443 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008444 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008445 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008446}
8447
Andreas Gampe4835d212018-11-21 14:55:10 -08008448template <typename T>
8449ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, T referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008450 StackHandleScope<2> hs(Thread::Current());
8451 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8452 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8453 return DoResolveType(type_idx, dex_cache, class_loader);
8454}
8455
Andreas Gampe4835d212018-11-21 14:55:10 -08008456// Instantiate the above.
8457template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8458 ArtField* referrer);
8459template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8460 ArtMethod* referrer);
8461template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8462 ObjPtr<mirror::Class> referrer);
8463
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008464ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008465 Handle<mirror::DexCache> dex_cache,
8466 Handle<mirror::ClassLoader> class_loader) {
8467 Thread* self = Thread::Current();
8468 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8469 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8470 if (resolved != nullptr) {
8471 // TODO: we used to throw here if resolved's class loader was not the
8472 // boot class loader. This was to permit different classes with the
8473 // same name to be loaded simultaneously by different loaders
8474 dex_cache->SetResolvedType(type_idx, resolved);
8475 } else {
8476 CHECK(self->IsExceptionPending())
8477 << "Expected pending exception for failed resolution of: " << descriptor;
8478 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8479 StackHandleScope<1> hs(self);
8480 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008481 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008482 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8483 self->ClearException();
8484 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8485 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008486 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008487 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008488 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008489 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008490 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008491}
8492
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008493ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8494 ObjPtr<mirror::DexCache> dex_cache,
8495 ObjPtr<mirror::ClassLoader> class_loader,
8496 uint32_t method_idx) {
8497 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8498 // functions can optimize the search if the dex_cache is the same as the DexCache
8499 // of the class, with fall-back to name and signature search otherwise.
8500 ArtMethod* resolved = nullptr;
8501 if (klass->IsInterface()) {
8502 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8503 } else {
8504 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8505 }
8506 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008507 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008508 hiddenapi::ShouldDenyAccessToMember(resolved,
8509 hiddenapi::AccessContext(class_loader, dex_cache),
8510 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008511 resolved = nullptr;
8512 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008513 if (resolved != nullptr) {
8514 // In case of jmvti, the dex file gets verified before being registered, so first
8515 // check if it's registered before checking class tables.
8516 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008517 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8518 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008519 << "DexFile referrer: " << dex_file.GetLocation()
8520 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8521 // Be a good citizen and update the dex cache to speed subsequent calls.
8522 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008523 // Disable the following invariant check as the verifier breaks it. b/73760543
8524 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8525 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8526 // << "Method: " << resolved->PrettyMethod() << ", "
8527 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8528 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008529 }
8530 return resolved;
8531}
8532
David Brazdil4525e0b2018-04-05 16:57:32 +01008533// Returns true if `method` is either null or hidden.
8534// Does not print any warnings if it is hidden.
8535static bool CheckNoSuchMethod(ArtMethod* method,
8536 ObjPtr<mirror::DexCache> dex_cache,
8537 ObjPtr<mirror::ClassLoader> class_loader)
8538 REQUIRES_SHARED(Locks::mutator_lock_) {
8539 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01008540 hiddenapi::ShouldDenyAccessToMember(method,
8541 hiddenapi::AccessContext(class_loader, dex_cache),
8542 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01008543}
8544
8545ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
8546 ObjPtr<mirror::DexCache> dex_cache,
8547 ObjPtr<mirror::ClassLoader> class_loader,
8548 uint32_t method_idx) {
8549 if (klass->IsInterface()) {
8550 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8551 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
8552 } else {
8553 // If there was an interface method with the same signature, we would have
8554 // found it in the "copied" methods. Only DCHECK that the interface method
8555 // really does not exist.
8556 if (kIsDebugBuild) {
8557 ArtMethod* method =
8558 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8559 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
8560 }
8561 return nullptr;
8562 }
8563}
8564
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08008565template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00008566ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07008567 Handle<mirror::DexCache> dex_cache,
8568 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008569 ArtMethod* referrer,
8570 InvokeType type) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008571 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01008572 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07008573 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01008574 PointerSize pointer_size = image_pointer_size_;
8575 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008576 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008577 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
8578 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01008579 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
8580 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07008581 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008582 return resolved;
8583 }
Vladimir Marko89011192017-12-11 13:45:05 +00008584 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008585 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008586 ObjPtr<mirror::Class> klass = nullptr;
8587 if (valid_dex_cache_method) {
8588 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
8589 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008590 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008591 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008592 // We normaly should not end up here. However the verifier currently doesn't guarantee
8593 // the invariant of having the klass in the class table. b/73760543
8594 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Marko6f1bd462017-12-06 17:45:03 +00008595 }
Vladimir Markoba118822017-06-12 15:41:56 +01008596 } else {
8597 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008598 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01008599 if (klass == nullptr) {
8600 DCHECK(Thread::Current()->IsExceptionPending());
8601 return nullptr;
8602 }
8603 }
8604
8605 // Check if the invoke type matches the class type.
8606 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07008607 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01008608 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07008609 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008610 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008611 }
Vladimir Markoba118822017-06-12 15:41:56 +01008612
8613 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008614 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008615 }
Vladimir Markoba118822017-06-12 15:41:56 +01008616
8617 // Note: We can check for IllegalAccessError only if we have a referrer.
8618 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
8619 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
8620 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8621 if (!referring_class->CheckResolvedMethodAccess(methods_class,
8622 resolved,
8623 dex_cache.Get(),
8624 method_idx,
8625 type)) {
8626 DCHECK(Thread::Current()->IsExceptionPending());
8627 return nullptr;
8628 }
8629 }
8630
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008631 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01008632 if (LIKELY(resolved != nullptr) &&
8633 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
8634 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07008635 return resolved;
8636 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008637 // If we had a method, or if we can find one with another lookup type,
8638 // it's an incompatible-class-change error.
8639 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01008640 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01008641 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008642 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008643 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008644 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01008645 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008646 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
8647 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01008648 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07008649 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08008650 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07008651 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07008652 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008653}
8654
Vladimir Marko89011192017-12-11 13:45:05 +00008655ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00008656 Handle<mirror::DexCache> dex_cache,
8657 Handle<mirror::ClassLoader> class_loader) {
8658 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008659 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01008660 if (resolved != nullptr) {
8661 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00008662 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
8663 return resolved;
8664 }
8665 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008666 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008667 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00008668 if (klass == nullptr) {
8669 Thread::Current()->AssertPendingException();
8670 return nullptr;
8671 }
8672 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01008673 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
8674 } else {
8675 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00008676 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008677 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008678 hiddenapi::ShouldDenyAccessToMember(
8679 resolved,
8680 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
8681 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008682 resolved = nullptr;
8683 }
Jeff Hao13e748b2015-08-25 20:44:19 +00008684 return resolved;
8685}
8686
Vladimir Markof44d36c2017-03-14 14:18:46 +00008687ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
8688 ObjPtr<mirror::DexCache> dex_cache,
8689 ObjPtr<mirror::ClassLoader> class_loader,
8690 bool is_static) {
8691 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008692 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008693 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
8694 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008695 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008696 }
8697 if (klass == nullptr) {
8698 // The class has not been resolved yet, so the field is also unresolved.
8699 return nullptr;
8700 }
8701 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00008702
David Brazdil1ab0fa82018-05-04 11:28:03 +01008703 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00008704}
8705
Vladimir Markoe11dd502017-12-08 14:09:45 +00008706ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008707 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008708 Handle<mirror::ClassLoader> class_loader,
8709 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008710 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008711 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008712 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008713 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008714 return resolved;
8715 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008716 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008717 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008718 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008719 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08008720 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07008721 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008722 }
8723
David Brazdil1ab0fa82018-05-04 11:28:03 +01008724 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07008725 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08008726 const char* name = dex_file.GetFieldName(field_id);
8727 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008728 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008729 }
Ian Rogersb067ac22011-12-13 18:05:09 -08008730 return resolved;
8731}
8732
Vladimir Markoe11dd502017-12-08 14:09:45 +00008733ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07008734 Handle<mirror::DexCache> dex_cache,
8735 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008736 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008737 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07008738 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07008739 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008740 return resolved;
8741 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00008742 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008743 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008744 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008745 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08008746 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008747 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08008748 }
8749
David Brazdil1ab0fa82018-05-04 11:28:03 +01008750 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
8751 if (resolved == nullptr) {
8752 const char* name = dex_file.GetFieldName(field_id);
8753 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00008754 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008755 }
8756 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07008757}
8758
David Brazdil1ab0fa82018-05-04 11:28:03 +01008759ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
8760 ObjPtr<mirror::DexCache> dex_cache,
8761 ObjPtr<mirror::ClassLoader> class_loader,
8762 uint32_t field_idx,
8763 bool is_static) {
8764 ArtField* resolved = nullptr;
8765 Thread* self = is_static ? Thread::Current() : nullptr;
8766 const DexFile& dex_file = *dex_cache->GetDexFile();
8767
8768 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
8769 : klass->FindInstanceField(dex_cache, field_idx);
8770
8771 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008772 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008773 const char* name = dex_file.GetFieldName(field_id);
8774 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8775 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
8776 : klass->FindInstanceField(name, type);
8777 }
8778
8779 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008780 hiddenapi::ShouldDenyAccessToMember(resolved,
8781 hiddenapi::AccessContext(class_loader, dex_cache),
8782 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008783 resolved = nullptr;
8784 }
8785
8786 if (resolved != nullptr) {
8787 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8788 }
8789
8790 return resolved;
8791}
8792
8793ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
8794 ObjPtr<mirror::DexCache> dex_cache,
8795 ObjPtr<mirror::ClassLoader> class_loader,
8796 uint32_t field_idx) {
8797 ArtField* resolved = nullptr;
8798 Thread* self = Thread::Current();
8799 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008800 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01008801
8802 const char* name = dex_file.GetFieldName(field_id);
8803 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
8804 resolved = mirror::Class::FindField(self, klass, name, type);
8805
8806 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008807 hiddenapi::ShouldDenyAccessToMember(resolved,
8808 hiddenapi::AccessContext(class_loader, dex_cache),
8809 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01008810 resolved = nullptr;
8811 }
8812
8813 if (resolved != nullptr) {
8814 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
8815 }
8816
8817 return resolved;
8818}
8819
Vladimir Markoaf940202017-12-08 15:01:18 +00008820ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
8821 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008822 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008823 Handle<mirror::DexCache> dex_cache,
8824 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008825 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08008826 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008827
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008828 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008829 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01008830 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01008831 }
8832
Narayan Kamath25352fc2016-08-03 12:46:58 +01008833 StackHandleScope<4> hs(self);
8834
8835 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00008836 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008837 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008838 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008839 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008840 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008841 DCHECK(self->IsExceptionPending());
8842 return nullptr;
8843 }
8844
8845 // Then resolve the argument types.
8846 //
8847 // TODO: Is there a better way to figure out the number of method arguments
8848 // other than by looking at the shorty ?
8849 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
8850
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008851 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01008852 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8853 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008854 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008855 DCHECK(self->IsExceptionPending());
8856 return nullptr;
8857 }
8858
8859 DexFileParameterIterator it(dex_file, proto_id);
8860 int32_t i = 0;
8861 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
8862 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08008863 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008864 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008865 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01008866 DCHECK(self->IsExceptionPending());
8867 return nullptr;
8868 }
8869
8870 method_params->Set(i++, param_class.Get());
8871 }
8872
8873 DCHECK(!it.HasNext());
8874
8875 Handle<mirror::MethodType> type = hs.NewHandle(
8876 mirror::MethodType::Create(self, return_type, method_params));
8877 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
8878
8879 return type.Get();
8880}
8881
Vladimir Markoaf940202017-12-08 15:01:18 +00008882ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01008883 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00008884 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01008885 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01008886 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8887 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00008888 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01008889}
8890
Vladimir Marko5aead702019-03-27 11:00:36 +00008891ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008892 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08008893 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008894 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008895 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008896 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
8897 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008898 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008899 bool is_static;
8900 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00008901 switch (handle_type) {
8902 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008903 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008904 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008905 is_static = true;
8906 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01008907 break;
8908 }
8909 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008910 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008911 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008912 is_static = true;
8913 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01008914 break;
8915 }
8916 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01008917 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008918 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008919 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008920 num_params = 2;
8921 break;
8922 }
8923 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008924 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008925 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008926 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00008927 num_params = 1;
8928 break;
8929 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008930 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01008931 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008932 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01008933 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008934 case DexFile::MethodHandleType::kInvokeInterface:
8935 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00008936 }
8937
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008938 ArtField* target_field =
8939 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
8940 if (LIKELY(target_field != nullptr)) {
8941 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
8942 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
8943 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
8944 ThrowIllegalAccessErrorField(referring_class, target_field);
8945 return nullptr;
8946 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00008947 if (UNLIKELY(is_put && target_field->IsFinal())) {
8948 ThrowIllegalAccessErrorField(referring_class, target_field);
8949 return nullptr;
8950 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008951 } else {
8952 DCHECK(Thread::Current()->IsExceptionPending());
8953 return nullptr;
8954 }
8955
8956 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008957 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00008958 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
8959 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01008960 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00008961 DCHECK(self->IsExceptionPending());
8962 return nullptr;
8963 }
8964
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008965 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00008966 Handle<mirror::Class> return_type;
8967 switch (handle_type) {
8968 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008969 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008970 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008971 break;
8972 }
8973 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008974 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008975 break;
8976 }
8977 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01008978 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008979 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00008980 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00008981 break;
8982 }
8983 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01008984 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00008985 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00008986 break;
8987 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008988 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01008989 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008990 case DexFile::MethodHandleType::kInvokeConstructor:
8991 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01008992 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01008993 UNREACHABLE();
8994 }
8995
8996 for (int32_t i = 0; i < num_params; ++i) {
8997 if (UNLIKELY(method_params->Get(i) == nullptr)) {
8998 DCHECK(self->IsExceptionPending());
8999 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00009000 }
9001 }
9002
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009003 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009004 DCHECK(self->IsExceptionPending());
9005 return nullptr;
9006 }
9007
9008 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009009 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9010 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009011 DCHECK(self->IsExceptionPending());
9012 return nullptr;
9013 }
Orion Hodson631827d2017-04-10 14:53:47 +01009014
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009015 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
9016 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9017}
9018
Vladimir Marko5aead702019-03-27 11:00:36 +00009019ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009020 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009021 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009022 ArtMethod* referrer) {
9023 DexFile::MethodHandleType handle_type =
9024 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9025 mirror::MethodHandle::Kind kind;
9026 uint32_t receiver_count = 0;
9027 ArtMethod* target_method = nullptr;
9028 switch (handle_type) {
9029 case DexFile::MethodHandleType::kStaticPut:
9030 case DexFile::MethodHandleType::kStaticGet:
9031 case DexFile::MethodHandleType::kInstancePut:
9032 case DexFile::MethodHandleType::kInstanceGet:
9033 UNREACHABLE();
9034 case DexFile::MethodHandleType::kInvokeStatic: {
9035 kind = mirror::MethodHandle::Kind::kInvokeStatic;
9036 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009037 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9038 method_handle.field_or_method_idx_,
9039 referrer,
9040 InvokeType::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009041 break;
9042 }
9043 case DexFile::MethodHandleType::kInvokeInstance: {
9044 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
9045 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009046 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9047 method_handle.field_or_method_idx_,
9048 referrer,
9049 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009050 break;
9051 }
9052 case DexFile::MethodHandleType::kInvokeConstructor: {
9053 // Constructors are currently implemented as a transform. They
9054 // are special cased later in this method.
9055 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9056 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009057 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9058 method_handle.field_or_method_idx_,
9059 referrer,
9060 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009061 break;
9062 }
9063 case DexFile::MethodHandleType::kInvokeDirect: {
9064 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9065 receiver_count = 1;
9066 StackHandleScope<2> hs(self);
9067 // A constant method handle with type kInvokeDirect can refer to
9068 // a method that is private or to a method in a super class. To
9069 // disambiguate the two options, we resolve the method ignoring
9070 // the invocation type to determine if the method is private. We
9071 // then resolve again specifying the intended invocation type to
9072 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009073 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009074 hs.NewHandle(referrer->GetDexCache()),
9075 hs.NewHandle(referrer->GetClassLoader()));
9076 if (UNLIKELY(target_method == nullptr)) {
9077 break;
9078 }
9079
9080 if (target_method->IsPrivate()) {
9081 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009082 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9083 method_handle.field_or_method_idx_,
9084 referrer,
9085 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009086 } else {
9087 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009088 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9089 method_handle.field_or_method_idx_,
9090 referrer,
9091 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009092 if (UNLIKELY(target_method == nullptr)) {
9093 break;
9094 }
9095 // Find the method specified in the parent in referring class
9096 // so invoke-super invokes the method in the parent of the
9097 // referrer.
9098 target_method =
9099 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9100 kRuntimePointerSize);
9101 }
9102 break;
9103 }
9104 case DexFile::MethodHandleType::kInvokeInterface: {
9105 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9106 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009107 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9108 method_handle.field_or_method_idx_,
9109 referrer,
9110 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009111 break;
9112 }
Orion Hodson631827d2017-04-10 14:53:47 +01009113 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009114
9115 if (UNLIKELY(target_method == nullptr)) {
9116 DCHECK(Thread::Current()->IsExceptionPending());
9117 return nullptr;
9118 }
9119
9120 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9121 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9122 uint32_t access_flags = target_method->GetAccessFlags();
9123 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9124 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9125 return nullptr;
9126 }
9127
9128 // Calculate the number of parameters from the method shorty. We add the
9129 // receiver count (0 or 1) and deduct one for the return value.
9130 uint32_t shorty_length;
9131 target_method->GetShorty(&shorty_length);
9132 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9133
Orion Hodsonecd58562018-09-24 11:27:33 +01009134 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009135 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009136 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9137 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9138 if (method_params.Get() == nullptr) {
9139 DCHECK(self->IsExceptionPending());
9140 return nullptr;
9141 }
9142
Orion Hodsonecd58562018-09-24 11:27:33 +01009143 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009144 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009145 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009146 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009147 // Insert receiver. Use the class identified in the method handle rather than the declaring
9148 // class of the resolved method which may be super class or default interface method
9149 // (b/115964401).
9150 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9151 // receiver_class should have been resolved when resolving the target method.
9152 DCHECK(receiver_class != nullptr);
9153 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009154 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009155
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009156 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009157 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009158 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009159 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009160 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009161 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009162 if (nullptr == klass) {
9163 DCHECK(self->IsExceptionPending());
9164 return nullptr;
9165 }
9166 method_params->Set(index++, klass);
9167 it.Next();
9168 }
9169
Orion Hodsonecd58562018-09-24 11:27:33 +01009170 Handle<mirror::Class> return_type =
9171 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009172 if (UNLIKELY(return_type.IsNull())) {
9173 DCHECK(self->IsExceptionPending());
9174 return nullptr;
9175 }
9176
9177 Handle<mirror::MethodType>
9178 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9179 if (UNLIKELY(method_type.IsNull())) {
9180 DCHECK(self->IsExceptionPending());
9181 return nullptr;
9182 }
9183
9184 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9185 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9186 Handle<mirror::MethodHandlesLookup> lookup =
9187 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9188 return lookup->FindConstructor(self, constructor_class, method_type);
9189 }
9190
9191 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9192 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9193}
9194
Vladimir Markoaf940202017-12-08 15:01:18 +00009195ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9196 uint32_t method_handle_idx,
9197 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009198 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009199 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009200 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009201 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9202 case DexFile::MethodHandleType::kStaticPut:
9203 case DexFile::MethodHandleType::kStaticGet:
9204 case DexFile::MethodHandleType::kInstancePut:
9205 case DexFile::MethodHandleType::kInstanceGet:
9206 return ResolveMethodHandleForField(self, method_handle, referrer);
9207 case DexFile::MethodHandleType::kInvokeStatic:
9208 case DexFile::MethodHandleType::kInvokeInstance:
9209 case DexFile::MethodHandleType::kInvokeConstructor:
9210 case DexFile::MethodHandleType::kInvokeDirect:
9211 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009212 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009213 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009214}
9215
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009216bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9217 return (entry_point == GetQuickResolutionStub()) ||
9218 (quick_resolution_trampoline_ == entry_point);
9219}
9220
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009221bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9222 return (entry_point == GetQuickToInterpreterBridge()) ||
9223 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9224}
9225
9226bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9227 return (entry_point == GetQuickGenericJniStub()) ||
9228 (quick_generic_jni_trampoline_ == entry_point);
9229}
9230
David Sehra49e0532017-08-25 08:05:29 -07009231bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
9232 return entry_point == GetJniDlsymLookupStub();
9233}
9234
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009235const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9236 return GetQuickGenericJniStub();
9237}
9238
Mathieu Chartiere401d142015-04-22 13:56:20 -07009239void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009240 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009241 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9242 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009243 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009244 }
9245}
9246
Alex Lightdb01a092017-04-03 15:39:55 -07009247void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9248 DCHECK(method->IsObsolete());
9249 // We cannot mess with the entrypoints of native methods because they are used to determine how
9250 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9251 if (!method->IsNative()) {
9252 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9253 }
9254}
9255
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009256void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009257 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009258 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009259 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9260 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009261 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9262 os << "Dumping registered class loaders\n";
9263 size_t class_loader_index = 0;
9264 for (const ClassLoaderData& class_loader : class_loaders_) {
9265 ObjPtr<mirror::ClassLoader> loader =
9266 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9267 if (loader != nullptr) {
9268 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9269 bool saw_one_dex_file = false;
9270 for (const DexCacheData& dex_cache : dex_caches_) {
9271 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9272 if (saw_one_dex_file) {
9273 os << ":";
9274 }
9275 saw_one_dex_file = true;
9276 os << dex_cache.dex_file->GetLocation();
9277 }
9278 }
9279 os << "]";
9280 bool found_parent = false;
9281 if (loader->GetParent() != nullptr) {
9282 size_t parent_index = 0;
9283 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9284 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9285 soa.Self()->DecodeJObject(class_loader2.weak_root));
9286 if (loader2 == loader->GetParent()) {
9287 os << ", parent #" << parent_index;
9288 found_parent = true;
9289 break;
9290 }
9291 parent_index++;
9292 }
9293 if (!found_parent) {
9294 os << ", unregistered parent of type "
9295 << loader->GetParent()->GetClass()->PrettyDescriptor();
9296 }
9297 } else {
9298 os << ", no parent";
9299 }
9300 os << "\n";
9301 }
9302 }
9303 os << "Done dumping class loaders\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009304}
9305
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009306class CountClassesVisitor : public ClassLoaderVisitor {
9307 public:
9308 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9309
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009310 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009311 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009312 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009313 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009314 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9315 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009316 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009317 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009318
9319 size_t num_zygote_classes;
9320 size_t num_non_zygote_classes;
9321};
9322
9323size_t ClassLinker::NumZygoteClasses() const {
9324 CountClassesVisitor visitor;
9325 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009326 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009327}
9328
9329size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009330 CountClassesVisitor visitor;
9331 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009332 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009333}
9334
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009335size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009336 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009337 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009338 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009339}
9340
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009341pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009342 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009343}
9344
9345pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009346 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009347}
9348
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009349void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009350 DCHECK(!init_done_);
9351
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009352 DCHECK(klass != nullptr);
9353 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009354
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009355 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009356 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009357 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9358 int32_t index = static_cast<int32_t>(class_root);
9359 DCHECK(class_roots->Get(index) == nullptr);
9360 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009361}
9362
Roland Levillain0e840272018-08-23 19:55:30 +01009363void ClassLinker::AllocAndSetPrimitiveArrayClassRoot(Thread* self,
9364 ObjPtr<mirror::Class> java_lang_Class,
9365 ClassRoot primitive_array_class_root,
9366 ClassRoot primitive_class_root,
9367 const char* descriptor) {
9368 StackHandleScope<1> hs(self);
9369 Handle<mirror::Class> primitive_array_class(hs.NewHandle(
9370 AllocPrimitiveArrayClass(self, java_lang_Class)));
9371 primitive_array_class->SetComponentType(GetClassRoot(primitive_class_root, this));
9372 SetClassRoot(primitive_array_class_root, primitive_array_class.Get());
9373 CheckSystemClass(self, primitive_array_class, descriptor);
9374}
9375
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009376ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9377 Thread* self,
9378 const std::vector<const DexFile*>& dex_files,
9379 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009380 Handle<mirror::ClassLoader> parent_loader,
9381 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009382
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009383 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009384
Mathieu Chartierc7853442015-03-27 14:35:38 -07009385 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009386 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009387
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009388 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009389 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009390 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009391 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009392 mirror::ObjectArray<mirror::Object>::Alloc(self,
9393 dex_elements_class.Get(),
9394 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009395 Handle<mirror::Class> h_dex_element_class =
9396 hs.NewHandle(dex_elements_class->GetComponentType());
9397
Mathieu Chartierc7853442015-03-27 14:35:38 -07009398 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009399 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009400 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009401
Andreas Gampe08883de2016-11-08 13:20:52 -08009402 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009403 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009404
Andreas Gampe08883de2016-11-08 13:20:52 -08009405 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009406 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009407
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009408 // Fill the elements array.
9409 int32_t index = 0;
9410 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009411 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009412
Calin Juravle7865ac72017-06-28 11:03:12 -07009413 // CreateWellKnownClassLoader is only used by gtests and compiler.
9414 // 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 -07009415 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9416 self,
9417 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009418 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009419 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009420
Mathieu Chartier3738e982017-05-12 16:07:28 -07009421 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9422 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009423 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009424 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009425 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009426 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009427
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009428 Handle<mirror::String> h_file_name = hs2.NewHandle(
9429 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009430 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009431 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9432
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009433 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009434 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009435 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009436
9437 h_dex_elements->Set(index, h_element.Get());
9438 index++;
9439 }
9440 DCHECK_EQ(index, h_dex_elements->GetLength());
9441
9442 // Create DexPathList.
9443 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009444 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009445 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009446 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009447 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009448 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9449 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9450 // elements.
9451 {
9452 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9453 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9454 DCHECK(native_lib_dirs != nullptr);
9455 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9456 DCHECK(list_class != nullptr);
9457 {
9458 StackHandleScope<1> h_list_scope(self);
9459 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9460 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9461 DCHECK(list_init);
9462 list_class = h_list_class.Get();
9463 }
9464 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9465 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9466 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9467 // normally never null), as long as one does not try to add elements, this will still
9468 // work.
9469 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9470 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009471
Calin Juravle7865ac72017-06-28 11:03:12 -07009472 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009473 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9474 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009475 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009476 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009477 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009478 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009479 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009480 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009481
9482 // Make a pretend boot-classpath.
9483 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009484 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009485 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009486 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009487 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009488 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009489 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009490 if (parent_loader.Get() == nullptr) {
9491 ScopedObjectAccessUnchecked soa(self);
9492 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9493 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9494 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9495 } else {
9496 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9497 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009498
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009499 ArtField* shared_libraries_field =
9500 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9501 DCHECK(shared_libraries_field != nullptr);
9502 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9503
9504 return h_class_loader.Get();
9505}
9506
9507jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9508 const std::vector<const DexFile*>& dex_files,
9509 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009510 jobject parent_loader,
9511 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009512 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9513 WellKnownClasses::dalvik_system_PathClassLoader) ||
9514 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +00009515 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
9516 self->GetJniEnv()->IsSameObject(loader_class,
9517 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009518
9519 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9520 // We could move the jobject to the callers, but all call-sites do this...
9521 ScopedObjectAccessUnchecked soa(self);
9522
9523 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009524 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009525
9526 Handle<mirror::Class> h_loader_class =
9527 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009528 Handle<mirror::ClassLoader> h_parent =
9529 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9530 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9531 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009532
9533 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
9534 self,
9535 dex_files,
9536 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009537 h_parent,
9538 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009539
9540 // Make it a global ref and return.
9541 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009542 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009543 return soa.Env()->NewGlobalRef(local_ref.get());
9544}
9545
Calin Juravle7865ac72017-06-28 11:03:12 -07009546jobject ClassLinker::CreatePathClassLoader(Thread* self,
9547 const std::vector<const DexFile*>& dex_files) {
9548 return CreateWellKnownClassLoader(self,
9549 dex_files,
9550 WellKnownClasses::dalvik_system_PathClassLoader,
9551 nullptr);
9552}
9553
Andreas Gampe8ac75952015-06-02 21:01:45 -07009554void ClassLinker::DropFindArrayClassCache() {
9555 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
9556 find_array_class_cache_next_victim_ = 0;
9557}
9558
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009559void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009560 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009561 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -07009562 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009563 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
9564 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009565 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +01009566 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009567 }
9568 }
9569}
9570
Alexey Grebenkin252a4e42018-04-02 18:18:01 +03009571void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
9572 for (const ClassLoaderData& data : class_loaders_) {
9573 LinearAlloc* alloc = data.allocator;
9574 if (alloc != nullptr && !visitor->Visit(alloc)) {
9575 break;
9576 }
9577 }
9578}
9579
Mathieu Chartierbc5a7952016-10-17 15:46:31 -07009580void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
9581 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009582 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009583 Thread* const self = Thread::Current();
9584 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +01009585 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009586 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07009587 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -07009588 // It was not already inserted, perform the write barrier to let the GC know the class loader's
9589 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07009590 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -07009591 }
9592}
9593
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07009594void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009595 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -07009596 std::vector<ClassLoaderData> to_delete;
9597 // Do the delete outside the lock to avoid lock violation in jit code cache.
9598 {
9599 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
9600 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
9601 const ClassLoaderData& data = *it;
9602 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -07009603 ObjPtr<mirror::ClassLoader> class_loader =
9604 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -07009605 if (class_loader != nullptr) {
9606 ++it;
9607 } else {
9608 VLOG(class_linker) << "Freeing class loader";
9609 to_delete.push_back(data);
9610 it = class_loaders_.erase(it);
9611 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009612 }
9613 }
Mathieu Chartier65975772016-08-05 10:46:36 -07009614 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03009615 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009616 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -07009617 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009618}
9619
Vladimir Marko21300532017-01-24 18:06:55 +00009620class GetResolvedClassesVisitor : public ClassVisitor {
9621 public:
9622 GetResolvedClassesVisitor(std::set<DexCacheResolvedClasses>* result, bool ignore_boot_classes)
9623 : result_(result),
9624 ignore_boot_classes_(ignore_boot_classes),
9625 last_resolved_classes_(result->end()),
9626 last_dex_file_(nullptr),
9627 vlog_is_on_(VLOG_IS_ON(class_linker)),
9628 extra_stats_(),
9629 last_extra_stats_(extra_stats_.end()) { }
9630
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009631 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko21300532017-01-24 18:06:55 +00009632 if (!klass->IsProxyClass() &&
9633 !klass->IsArrayClass() &&
9634 klass->IsResolved() &&
9635 !klass->IsErroneousResolved() &&
9636 (!ignore_boot_classes_ || klass->GetClassLoader() != nullptr)) {
9637 const DexFile& dex_file = klass->GetDexFile();
9638 if (&dex_file != last_dex_file_) {
9639 last_dex_file_ = &dex_file;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07009640 DexCacheResolvedClasses resolved_classes(
9641 dex_file.GetLocation(),
9642 DexFileLoader::GetBaseLocation(dex_file.GetLocation()),
9643 dex_file.GetLocationChecksum(),
9644 dex_file.NumMethodIds());
Vladimir Marko21300532017-01-24 18:06:55 +00009645 last_resolved_classes_ = result_->find(resolved_classes);
9646 if (last_resolved_classes_ == result_->end()) {
9647 last_resolved_classes_ = result_->insert(resolved_classes).first;
9648 }
9649 }
9650 bool added = last_resolved_classes_->AddClass(klass->GetDexTypeIndex());
9651 if (UNLIKELY(vlog_is_on_) && added) {
9652 const DexCacheResolvedClasses* resolved_classes = std::addressof(*last_resolved_classes_);
9653 if (last_extra_stats_ == extra_stats_.end() ||
9654 last_extra_stats_->first != resolved_classes) {
9655 last_extra_stats_ = extra_stats_.find(resolved_classes);
9656 if (last_extra_stats_ == extra_stats_.end()) {
9657 last_extra_stats_ =
9658 extra_stats_.emplace(resolved_classes, ExtraStats(dex_file.NumClassDefs())).first;
9659 }
9660 }
9661 }
9662 }
9663 return true;
9664 }
9665
9666 void PrintStatistics() const {
9667 if (vlog_is_on_) {
9668 for (const DexCacheResolvedClasses& resolved_classes : *result_) {
9669 auto it = extra_stats_.find(std::addressof(resolved_classes));
9670 DCHECK(it != extra_stats_.end());
9671 const ExtraStats& extra_stats = it->second;
9672 LOG(INFO) << "Dex location " << resolved_classes.GetDexLocation()
9673 << " has " << resolved_classes.GetClasses().size() << " / "
9674 << extra_stats.number_of_class_defs_ << " resolved classes";
9675 }
9676 }
9677 }
9678
9679 private:
9680 struct ExtraStats {
9681 explicit ExtraStats(uint32_t number_of_class_defs)
9682 : number_of_class_defs_(number_of_class_defs) {}
9683 uint32_t number_of_class_defs_;
9684 };
9685
9686 std::set<DexCacheResolvedClasses>* result_;
9687 bool ignore_boot_classes_;
9688 std::set<DexCacheResolvedClasses>::iterator last_resolved_classes_;
9689 const DexFile* last_dex_file_;
9690
9691 // Statistics.
9692 bool vlog_is_on_;
9693 std::map<const DexCacheResolvedClasses*, ExtraStats> extra_stats_;
9694 std::map<const DexCacheResolvedClasses*, ExtraStats>::iterator last_extra_stats_;
9695};
9696
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009697std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08009698 ScopedTrace trace(__PRETTY_FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009699 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier268764d2016-09-13 12:09:38 -07009700 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009701 std::set<DexCacheResolvedClasses> ret;
9702 VLOG(class_linker) << "Collecting resolved classes";
9703 const uint64_t start_time = NanoTime();
Vladimir Marko21300532017-01-24 18:06:55 +00009704 GetResolvedClassesVisitor visitor(&ret, ignore_boot_classes);
9705 VisitClasses(&visitor);
9706 if (VLOG_IS_ON(class_linker)) {
9707 visitor.PrintStatistics();
9708 LOG(INFO) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009709 }
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08009710 return ret;
9711}
9712
Mathieu Chartier65975772016-08-05 10:46:36 -07009713class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
9714 public:
9715 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
9716 : method_(method),
9717 pointer_size_(pointer_size) {}
9718
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009719 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -07009720 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
9721 holder_ = klass;
9722 }
9723 // Return false to stop searching if holder_ is not null.
9724 return holder_ == nullptr;
9725 }
9726
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009727 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -07009728 const ArtMethod* const method_;
9729 const PointerSize pointer_size_;
9730};
9731
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009732ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -07009733 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
9734 CHECK(method->IsCopied());
9735 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
9736 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009737 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -07009738}
9739
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009740ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
9741 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009742 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009743 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009744 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -08009745}
9746
Roland Levillain0e840272018-08-23 19:55:30 +01009747// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +01009748template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009749 uint32_t method_idx,
9750 Handle<mirror::DexCache> dex_cache,
9751 Handle<mirror::ClassLoader> class_loader,
9752 ArtMethod* referrer,
9753 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +01009754template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009755 uint32_t method_idx,
9756 Handle<mirror::DexCache> dex_cache,
9757 Handle<mirror::ClassLoader> class_loader,
9758 ArtMethod* referrer,
9759 InvokeType type);
9760
Roland Levillain0e840272018-08-23 19:55:30 +01009761// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009762template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +01009763 Thread* self,
9764 ObjPtr<mirror::Class> java_lang_Class,
9765 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009766template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +01009767 Thread* self,
9768 ObjPtr<mirror::Class> java_lang_Class,
9769 uint32_t class_size);
9770
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009771} // namespace art